利用java8的新特性stream实现list数据去重

一、根据列表中的对象去重

List list=new ArrayList<>();

list.add("a");

list.add("b");

list.add("b");

//核心方法distinct()

list.stream().distinct().forEach(item ->System.out.println(item));

输出:"a"

           "b"

二、根据列表中的对象的元素去重

List cartStoreList =new ArrayList<>();

cartStoreList.add(new ShoppingCartStore("a","好菜"));

cartStoreList.add(new ShoppingCartStore("b","坏菜"));

cartStoreList.add(new ShoppingCartStore("b","好坏菜"));

cartStoreList.stream().distinct().forEach(scStore ->{

System.out.println(scStore.getStoreId())

});

其实和对象去重一样,只是要重写一下hashCode()和equals()方法。见下图

你可能感兴趣的:(利用java8的新特性stream实现list数据去重)