上次对Stream流来进行分组的文章很多人看,想看的可以来这:
Stream流来进行集合分组
这次小编又带来Stream的去重,话不多数,直接上代码:

这是对简单数据类型的去重

		//字符串集合进行简单的去重(其他数据类型去重一样)
        List<String> stringList = Arrays.asList("伽罗", "貂蝉", "芈月", "伽罗");

        //jdk1.8Stream来去重
        stringList = stringList.stream().distinct().collect(Collectors.toList());

        System.out.println(JSON.toJSONString(stringList));

        /**
         * 执行结果:["伽罗","貂蝉","芈月"]
         *
         */

对对象中的某一个属性来进行去重:

/**
实体类
*/
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//lombok简化代码
@AllArgsConstructor
@NoArgsConstructor
public class Hero {

    //英雄id
    private int id;

    //名字
    private String name;

    //类型
    private String type;
}
		//进行对象中的某个属性进行去重
        List<Hero> list = Arrays.asList(
                new Hero(001,"孙悟空","刺客"),
                new Hero(002,"韩信","刺客"),
                new Hero(003,"伽罗","射手"),
                new Hero(004,"阿狸","射手"),
                new Hero(005,"貂蝉","法师"));

        //需求:每一个职业只能保留一个英雄
        //去重规则,先出现的保存,后出现的被去掉
        list = list.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Hero::getType))), ArrayList::new));

        System.out.println(JSON.toJSONString(list));

        /**
         * 执行结果:[{"id":1,"name":"孙悟空","type":"刺客"},{"id":3,"name":"伽罗","type":"射手"},
         * {"id":5,"name":"貂蝉","type":"法师"}]
         */

这样就学会了,直接复制代码运行一下,照猫画虎不是难题,有什么问题请留言,还请各位大佬批评指正!!!!

Q.E.D.