当前位置: 代码迷 >> 综合 >> lambda表达式操作集合数据(下)
  详细解决方案

lambda表达式操作集合数据(下)

热度:30   发布时间:2024-01-25 01:15:57.0
//4.Stream中常见的api操作List<String> accountList = new ArrayList<>();accountList.add("songjiang");accountList.add("lujinyi");accountList.add("wuyong");accountList.add("linchong");accountList.add("luzhishen");accountList.add("likui");accountList.add("wusong");
//1.map中间操作,map()方法接受一个Functional接口accountList = accountList.stream().map(x -> "梁山好汉" + x).collect(Collectors.toList());accountList.forEach(System.out::println);
//2.fiilter()添加过滤条件,过滤符合条件的用户accountList = accountList.stream().filter(x -> x.length() > 5).collect(Collectors.toList());accountList.forEach(System.out::println);
//3.foreach 增强for循环accountList.forEach(x-> System.out.println("foreach->"+x));accountList.forEach(x-> System.out.println("foreach->"+x));accountList.forEach(x-> System.out.println("foreach->"+x));
//4.peek()中间操作,迭代数据完成数据的一次处理过程accountList.stream().peek(x -> System.out.println("peek1" + x)).peek(x -> System.out.println("peek2" + x)).forEach(System.out::println);//5.Stream中对数字运算符的支持List<Integer> integers = new ArrayList<>();integers.add(1);integers.add(221);integers.add(111);integers.add(11);integers.add(123);integers.add(1889);integers.add(132232);integers.add(3242);//1.skip()中间操作,有状态,跳过部分数据List<Integer> integerList = integers.stream().skip(3).collect(Collectors.toList());integerList.forEach(System.out::println);//2.limit()操作,有状态,限制输出数据量List<Integer> integerList = integers.stream().skip(3).limit(2).collect(Collectors.toList());integerList.forEach(System.out::println);//3.distinct去除重复的数据List<Integer> integerList = integers.stream().distinct().collect(Collectors.toList());integerList.forEach(System.out::println);//4.sort排序操作List<Integer> integerList = integers.stream().sorted((x,y)->x-y).collect(Collectors.toList());integerList.forEach(System.out::println);//5.max min获取最大最小值Optional<Integer> optional = integers.stream().max((x, y) -> x - y);System.out.println(optional.get());//6.reduce()合并处理数据Optional<Integer> reduce = integers.stream().reduce((sum, x) -> sum + x);System.out.println(reduce.get());}