Java8新特性 利用流和Lambda表达式对List集合进行处理

最近在做项目的过程中经常会接触到 lambda 表达式,随后发现它基本上可以替代所有 for 循环,包括增强for循环。也就是我认为,绝大部分的for循环都可以用 lambda 表达式改写。

lambda表达式有它自己的优点:(1)简洁,(2)易并行计算。尤其适用于遍历结果,循环计算数值或者赋值的时候非常方便。

缺点: (1)若不用并行计算,很多时候计算速度没有比传统的 for 循环快。

   (2)不容易使用debug模式调试。

   (3)在 lambda 语句中直接强制类型转换不方便。

   (4)不可以在foreach中修改foreach外面的值。


public class Jdk8Main {
 
    public static void main(String[] args) {
        List<Person> list = new ArrayList<>();
        Person p1 = new Person("张1",1,1);
        Person p101 = new Person("张101",101,101);
        Person p2 = new Person("张2",2,2);
        Person p3 = new Person("张3",3,3);
        Person p4 = new Person("张4",4,4);
        Person p5 = new Person("张5",5,5);
        Person p6 = new Person("张6",6,6);
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        list.add(p5);
        list.add(p6);
        list.add(p101);
        
        /**
         * 1.forEach()进行遍历集合
         *    item:可以是任意值。类似于for循环中的循环值
         */
        list.forEach(item->{
            //设置值
            item.setName(item.getName()+"测试");;
            //输出语句
            System.out.println(item.toString());
        });
        
        /**
         * 2.stream()流操作
         */
        //2.1. 去重 distinct() 去重;collect(Collectors.toList())。封装成集合
        List<Person> distinctList =         
        list.stream().distinct().collect(Collectors.toList());
        //2.2 排序  sorted((第一个对象,第二个对象)->返回值)  (升降序看是第几个对象与第几个对象比较)
        List<Person> sortedList = list.stream().sorted((o1,o2)->o1.getAge()-o2.getAge()).collect(Collectors.toList());
        //2.3 过滤 , filter(item->{})   item为每一项。 按照自己的需求来筛选list中的数据
        List<Person> filterList = list.stream().filter(item->item.getAge()>3).collect(Collectors.toList());
        //2.4 map(), 提取对象中的某一元素.  用每一项来获得属性(也可以直接用  对象::get属性())
        List<String> mapList1 = list.stream().map(Person::getName).collect(Collectors.toList());
        List<String> mapList2 = list.stream().map(item->item.getName()).collect(Collectors.toList());
        //2.5 统计 sum() 。mapToDouble() 转换成double。还有其他类型转换。可以自己研究。
        //           max(),min(),average()
        double sum = list.stream().mapToDouble(Person::getAge).sum();
        //2.6 分组   Collectors.groupingBy(属性名)
        Map<Integer, List<Person>> map = list.stream().collect(Collectors.groupingBy(Person::getAge));
        //2.7 多重分组 Collectors.groupingBy(属性,Collectors.groupingBy(属性))
        Map<String, Map<Integer, List<Person>>> map2 = list.stream().collect(Collectors.groupingBy(t->t.getName(),Collectors.groupingBy(t->t.getAge())));
        //2.8 分组并计算综合        Collectors.summarizingLong()
        Map<String, Map<Integer, LongSummaryStatistics>> map3 = list.stream().collect(Collectors.groupingBy(t->t.getName(),Collectors.groupingBy(t->t.getAge(),Collectors.summarizingLong(Person::getSize))));
        
        /**
         *  3.  集合比较的简写方式
         */
        list.sort((o1,o2)->{return o1.getAge()-o2.getAge();});
    }
}

//找出2011年发生的所有交易,并按交易额排序(从低到高)
        List<Transaction> transactions1 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                .sorted(Comparator.comparingInt(Transaction::getValue))
                .collect(Collectors.toList());
        System.out.println(transactions1);
        //找出2011年发生的所有交易,并按交易额排序(从低到高)
        List<Transaction> transactions2 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                .sorted(Comparator.comparing(Transaction::getValue))
                .collect(Collectors.toList());
        System.out.println(transactions2);
        //找出2011年发生的所有交易,并按交易额排序(从高到低)
        List<Transaction> transactions3 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                //Comparator.comparing默认是升序排序,用reversed改成降序
                .sorted(Comparator.comparing(Transaction::getValue).reversed())
                .collect(Collectors.toList());
        System.out.println(transactions3);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值