栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java8对List去重

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java8对List去重

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private String name;
    private String sex;
    private Integer age;
}
  public static  void Test()
    {
        ArrayList listStudent = new ArrayList<>();
        listStudent.add(new Student("小明","男",10));
        listStudent.add(new Student("小花","女",8));
        listStudent.add(new Student("小李","男",9));
        listStudent.add(new Student("小刚","男",10));
        listStudent.add(new Student("小红","女",8));
        listStudent.add(new Student("小明","男",9));
		//按照age属性,对List进行去重处理
        listStudent = listStudent.stream()
            .collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getAge))), ArrayList::new));
        //打印结果
        listStudent.forEach(Student-> System.out.println(Student.toString()));
    }
     //运行结果
   Student(name=小花, sex=女, age=8)
   Student(name=小李, sex=男, age=9)
   Student(name=小明, sex=男, age=10)
//对于多属性去重
public static  void Test2()
    {
        ArrayList listStudent = new ArrayList<>();
        listStudent.add(new Student("小明","男",1));
        listStudent.add(new Student("小明","男",6));
        listStudent.add(new Student("小红","女",2));
        listStudent.add(new Student("小红","女",5));
        listStudent.add(new Student("小李","男",3));
        listStudent.add(new Student("小李","男",4));
        //根据name和sex两个属性去重,若两个属性都相同,则认为为相同
       List listTemp = listStudent.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new));
        //打印结果
        listTemp.forEach(Student-> System.out.println(Student.toString()));
    }
    //运行结果
    Student(name=小明, sex=男, age=1)
    Student(name=小李, sex=男, age=3)
   Student(name=小红, sex=女, age=2)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325591.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号