java8新特性-StreamAPI
StreamAPI
参考https://blog.csdn.net/y_k_y/article/details/84633001,仅自己学习记录,可劝删
Stream是用函数式编程在集合类上进行复杂操作的工具
一、流的生成方法
1.Collection接口的stream()
2.静态的stream.of
3.Arrays.stream
4.Stream.generate()方法生成无限流
...
二、流的中间操作
筛选
1 .filter()
ArrayList<Apple> apples = new ArrayList<>(); apples.add(new Apple(23,"lin")); apples.add(new Apple(42,"z")); apples.add(new Apple(44,"zhu")); apples.add(new Apple(40,"xiao")); apples.add(new Apple(17,"lin")); apples.add(new Apple(31,"z")); apples.add(new Apple(25,"xiao")); apples.add(new Apple(8,"z")); apples.add(new Apple(35,null)); List<Apple> appleList = apples.stream().filter(x -> x.getName() != null).collect(Collectors.toList()); appleList.forEach(System.out::println);
limit(n) 获取n个元素
skip(n) 跳过n元素
distinct():通过流元素的hashCode()和equals()去除重复元素
2.映射
map() :转换元素的值 会映射到每一个元素 生成新元素
map映射到每个元素对应的结果
List<Integer> integerList = apples.stream().map(Apple::getWeight).collect(Collectors.toList()); integerList.forEach(System.out::println);
3.排序
sorted():自然排序和自定义排序
public class Test { public static void main(String[] args) { ArrayList<Apple> apples = new ArrayList<>(); apples.add(new Apple(23,"lin")); apples.add(new Apple(42,"z")); apples.add(new Apple(44,"zhu")); apples.add(new Apple(40,"xiao")); apples.add(new Apple(17,"lin")); apples.add(new Apple(31,"z")); apples.add(new Apple(25,"xiao")); apples.add(new Apple(8,"z")); List<Integer> list = apples.stream().map(Apple::getWeight).collect(Collectors.toList()); //自然排序 List<Integer> appleList = list.stream().sorted().collect(Collectors.toList()); appleList.forEach(System.out::println); //自定义排序 List<Apple> apples1 = apples.stream().sorted(Comparator.comparing(Apple::getWeight)).collect(Collectors.toList()); apples1.forEach(System.out::println); } }
4.消费
peek:如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值
三、Collectors
Stream.collect() 是java 8 stream api中的终止方法。Collector接口实现对流中的元素重新包装
分组
public class Test { public static void main(String[] args) { ArrayList<Apple> apples = new ArrayList<>(); apples.add(new Apple(23,"lin")); apples.add(new Apple(42,"z")); apples.add(new Apple(44,"zhu")); apples.add(new Apple(40,"xiao")); apples.add(new Apple(17,"lin")); apples.add(new Apple(31,"z")); apples.add(new Apple(25,"xiao")); apples.add(new Apple(8,"z")); Map<String, List<Apple>> map = apples.stream().collect(Collectors.groupingBy(Apple::getName)); map.forEach((key,value)->{ System.out.println("key:"+key+",value"+value); }); } }
joining() 连接字符串流中的元素
Collectors.joining()
ArrayList<String> strings = new ArrayList<>(); strings.add("s"); strings.add("c"); strings.add("x"); String collect = strings.stream().collect(Collectors.joining(",", "(", ")")); System.out.println(collect);//(s,c,x) }