常用list,map操作之java8

分组和分区:

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

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

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

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

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

分区,最后分为两组,

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

1
{false=[Bob], true=[Alice, Charles, Dorothy]}

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

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....
    }
List<Person> persons = new ArrayList<>();

Person类里有id,id2,name属性

迭代输出:

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

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

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

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

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

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

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

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

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

排序

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

或者

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

筛选
找到第一个

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

找到全部

persons.stream().filter(a -> a.getHand().contains("ni")).collect(toList());
    原文作者:ykd2020
    原文地址: https://blog.csdn.net/yuankundong/article/details/78712826
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞