Stream流,大量的结合了Lambda的语法风格来编程,提供了一种更加强大,更加简单的方式操作集合或者数组的数据,代码更间接,可读性更好。
Stream的使用步骤
1.获取Stream流
//1.如何获取List集合的Stream流
List<String> names=new ArrayList<>();
Collections.addAll(names,"张三","张四","李四","王二麻");
Stream<String> stream=names.stream();
System.out.println(stream);
//2.如何获取set集合的Stream流
Set<String> set=new HashSet<>();
Collections.addAll(set,"刘德华","张曼玉","蜘蛛精","德玛西亚");
Stream<String> stream1=set.stream();
//打印包含 德 字的元素
stream1.filter(s->s.contains("德")).forEach(s->System.out.println(s));
//3.如何获取map集合的Stream流
Map<String,Double> map=new HashMap<>();
map.put("古力娜扎",172.3);
map.put("迪丽热巴",166.3);
map.put("马尔扎哈",156.3);
map.put("发士大夫",178.3);
//3.1第一种方法,分别获取key和value的stream流
Set<String> keySet = map.keySet();
Stream<String> ks= keySet.stream();
Collection<Double> values = map.values();
Stream<Double> val = values.stream();
//3.2第二种方法,通过entrySet()转成set集合获取stream流
Set<Map.Entry<String, Double>> entries = map.entrySet();
Stream<Map.Entry<String, Double>> entryStream = entries.stream();
entryStream.filter(e ->e.getKey().contains("巴")).forEach(e-> System.out.println(e.getKey()+"-->"+e.getValue()));
//4.数组如何获取Stream流
String[] strings={"zhagnsan","lisi","wnagerma"};
//4.1 通过Arrays.stream()
Stream<String> s1 = Arrays.stream(strings);
//4.2 通过Stream.of()
Stream<String> s2 = Stream.of(strings);
2.Stream流中常见的中间方法
例子:
3.Stream流常见的终结方法
例子:
4.收集Stream流
收集到数组中