//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());
}
来源:CSDN
作者:文泽稳
链接:https://blog.csdn.net/qq_31162311/article/details/104001223