流式传输带有重复对象的 distinct()

Stream distinct() with repeated objects

我有一个基本的 SpringBoot 2.0.6.RELEASE 应用程序。使用 Spring 初始化程序、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为具有 restful 架构的可执行 JAR 我有这个对象:

public class Menu  implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Long id;

     @Override
        public int hashCode() {
            return (int) (id ^ (id >>> 32));
        }



    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Menu menu = (Menu) o;

        return id == menu.id;
    }
...
}

我控制器里也有这段代码:

List<Menu> favoriteMenus = new ArrayList<Menu>();

        favoriteMenus.addAll(user.getFavoriteMenus());
        favoriteMenus.addAll(applicationProfileService
                .menusByProfile(user.getApplicationSetup().getApplicationProfile().getProfileKey()));

        favoriteMenus = 
                favoriteMenus
                    .stream()
                    .distinct()
                    .collect(Collectors.toList());

但是尽管 distinct() 列表中有重复的菜单

您正在测试 id 的引用相等性而不是它的值相等性(更多相关信息,例如 here), and id is a Long:

The Long class wraps a value of the primitive type long in an object.

id == menu.id 更改为 id.equals(menu.id),它应该可以工作(前提是此处没有其他错误)。