Stream的去重排序

1.List<Integer>排序

List<Integer> list = new ArrayList<>();list.add(50);list.add(25);list.add(25);list.add(98);list.add(32);List<Integer> collect = list.stream().distinct().sorted().collect(Collectors.toList());System.out.println("去重正序" + collect);List<Integer> collect1 = list.stream().distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());System.out.println("去重倒序" + collect1);打印结果去重正序[25, 32, 50, 98]去重倒序[98, 50, 32, 25]

 2.List<Person>的元素的属性值去重

Person p1 = new Person("张三", new BigDecimal("50.0"));Person p2 = new Person("王五", new BigDecimal("25.0"));Person p3 = new Person("李四", new BigDecimal("68.0"));Person p4 = new Person("赵六", new BigDecimal("17.0"));Person p5 = new Person("马八", new BigDecimal("25.0"));List<Person> list = new ArrayList<>();list.add(p1);list.add(p2);list.add(p3);list.add(p4);list.add(p5);List<Person> result = new LinkedList<>();for (Person person : list) { boolean b = result.stream().anyMatch(p -> p.getSalary().compareTo(person.getSalary())==0); if (!b) { result.add(person); }}System.out.println(result);打印结果:[{name='张三', salary=50.0}, {name='王五', salary=25.0}, {name='李四', salary=68.0}, {name='赵六', salary=17.0}]
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

我丢,去面试初级Java开发岗位,被问到泛型?

1、泛型的基础概念1.1为什么需要泛型cListlistnewArrayList();//默认类型是Objectlist.add("A123");list.add("B234");list.add("C345");System.out.println(list);

java8对集合的处理

publicstaticvoidmain(String\\args){List<StudentlistLists.newArrayList();list.add(newStudent("测试","男",18));list.add(newStudent("开发","男",20));list.add(n

[C#]ArrayList、string、string[]之间的转换

1、ArrarList转换为string\\:  ArrayListlistnewArrayList();  list.Add("aaa");  list.Add("bbb");  string\\arrString(string\\)list.ToArray(typeof(string));2、string\\转换

Java Lambda 常用案例

List类的Stream处理:List<StringlistnewArrayList<String();list.add("djk");list.add("djk1");list.add("djk12");//maplistlist.stream().ma

JSON的使用

一.json常用转换方法1.listListlistnewArrayList();list.add("first");list.add("second");JSONArrayjsonArray2JSONArray.fromObject(list);