分组和分区:

根据城市分组,结果存list型value

Map<String, List<Employee>> employeesByCity =
  employees.stream().collect(groupingBy(Employee::getCity));
  • 1
  • 2

也可以添加其他收集器,统计出每组的个数

Map<String, Long> numEmployeesByCity =
  employees.stream().collect(groupingBy(Employee::getCity, counting()));
  • 1
  • 2

将收集的结果转换为另一种类型: collectingAndThen

分区,最后分为两组,

Map<Boolean, List<Employee>> partitioned =
  employees.stream().collect(partitioningBy(e -> e.getNumSales() > 150));
输出如下结果:

1
{false=[Bob], true=[Alice, Charles, Dorothy]}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

当然,也可以分区后再分组

list操作

public static class Person{
        private Long id;
        private Long id2;
        private String name;
        private String age;
        private List<String> hand;

        public Person(Long id, Long id2, String name, String age, List<String> hand) {
            this.id = id;
            this.id2 = id2;
            this.name = name;
            this.age = age;
            this.hand = hand;
        }

        get,set....
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
List<Person> persons = new ArrayList<>();
  • 1

Person类里有id,id2,name属性

迭代输出:

persons.forEach(System.out::println);
persons.forEach(a-> System.out.println(a.getId()+"----"+a.getId2()+"--"+a.getName()));
  • 1
  • 2

根据属性去重,留最前面的一条(根据id和id2去重)

List<Person> unique = persons.stream().collect(
            collectingAndThen(
                toCollection(() -> new TreeSet<>(comparingLong(Person::getId).thenComparingLong(Person::getId2))), ArrayList::new)
        );
  • 1
  • 2
  • 3
  • 4

如果只有一个属性,不用加thenComparingLong

根据属性去重,留最后的一条

Map<String, Person> map= persons.stream().collect(Collectors.toMap(person->(person.getId2().toString()+person.getId().toString()), Function.identity(), (key1, key2) -> key2));
  • 1

Function.identity()的意思是取本身,(key1, key2) -> key2)是key重复后面的替代前面的

把对象里的list合并到一个list

List<String> hands = persons.stream().map(Person::getHand
        ).flatMap(List::stream).collect(toList());
  • 1
  • 2

排序

list  = l.stream().sorted((n1,n2)->n1.compareTo(n2)).collect(Collectors.toList());
  • 1

或者

list.sort((n1, n2) ->n1.compareTo(n2));
  • 1

筛选
找到第一个

persons.stream().filter(a -> a.getHand().contains("ni")).findFirst();//findAny是找到任何一个就返回
  • 1

找到全部

persons.stream().filter(a -> a.getHand().contains("ni")).collect(toList());

--------------------- 本文来自 ykd2020 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yuankundong/article/details/78712826?utm_source=copy

10-07 13:56