JDK1.8常用新特性常用生产记录

1.filter 过滤

List<String> lines = Arrays.asList("spring", "node", "mkyong","mkyong");
 //从集合中获取过滤后生成的集合
 List<String> list = lines.stream().filter(line-> !"mkyong".equals(line)).collect(Collectors.toList());

List<Person> persons = Arrays.asList(new Person("michael", 20),new Person("michael", 21), new Person("lawrence", 23));
//返回集合匹配到的第一个的age,如果都找不到返回orElse里面的值
Integer age = persons.stream().filter(x -> "michael".equals(x.getName())).map(Person::getAge).findFirst().orElse(null);
System.out.println(age);

2.map获取集合对象中指定元素集合(流)

List<Integer> l = persons.stream().filter(x -> "michael".equals(x.getName())).map(Person::getAge).collect(Collectors.toList());
System.out.println(l);//[20,21]

collect将流变成各种结果(收集器)
findAny返回集合流中任意一个个对象(一般返回第一个,并行时可能不会是第一个)
findFirst:返回流集合中第一个

3.groupby分组

        //1.分组计数
        List<Student> list1= Arrays.asList(
                new Student(1,"one","zhao"),new Student(2,"one","qian"),new Student(3,"two","sun"));
        //1.1根据某个属性分组计数
        Map<String,Long> result1=list1.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));
        System.out.println(result1);
        //1.2根据整个实体对象分组计数,当其为String时常使用
        Map<Student,Long> result2=list1.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
        System.out.println(result2);
        //1.3根据分组的key值对结果进行排序、放进另一个map中并输出
        Map<String,Long> xMap=new HashMap<>();
        result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByKey().reversed()) //reversed不生效
                .forEachOrdered(x->xMap.put(x.getKey(),x.getValue()));
        System.out.println(xMap);

        //2.分组,并统计其中一个属性值得sum或者avg:id总和
        Map<String,Integer> result3=list1.stream().collect(
                Collectors.groupingBy(Student::getGroupId,Collectors.summingInt(Student::getId))
        );
        System.out.println(result3);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值