Stream流的初体验:
package cn.chang.d8_stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest1 {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
Collections.addAll(names, "张三丰", "张无忌", "周芷若", "赵敏", "张强");
System.out.println(names);
// 找出姓张,且是3个字的名字,存入到一个新的集合中去
// List<String> list = new ArrayList<>();
// for (String name : names) {
// if(name.startsWith("张") && name.length() == 3) {
// list.add(name);
// }
// }
// System.out.println(list);
// 开始使用Stream流来解决这个需求:
List<String> list2 = names.stream().filter(s -> s.startsWith("张")).filter(a -> a.length() == 3).collect(Collectors.toList());
System.out.println(list2);
}
}
运行结果:
Stream流的使用步骤:
Stream流的常用方法:
获取Stream流:
获取集合的Stream流:
代码:
package cn.chang.d8_stream;
import java.util.*;
import java.util.stream.Stream;
public class StreamTest2 {
public static void main(String[] args) {
// 1. 如何获取List集合的Stream流?
List<String> names = new ArrayList<String>();
Collections.addAll(names, "张三丰", "张无忌", "周芷若", "赵敏", "张强");
Stream<String> stream = names.stream();
// 2. 如何获取Set集合的Stream流?
Set<String> set = new HashSet<String>();
Collections.addAll(set, "刘德华", "张曼玉", "蜘蛛精", "马德", "德玛西亚");
Stream<String> stream2 = set.stream();
stream2.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("迪丽热巴", 168.3);
map.put("马尔扎哈", 166.3);
map.put("卡尔扎巴", 168.3);
// map.Stream();
Set<String> keys = map.keySet();
Stream<String> ks = keys.stream();
Collection<Double> values = map.values();
Stream<Double> vs = values.stream();
Set<Map.Entry<String, Double>> entries = map.entrySet();
Stream<Map.Entry<String, Double>> kvs = entries.stream();
kvs.filter(e -> e.getKey().contains("巴")).forEach(e -> System.out.println(e.getKey() + "-->" + e.getValue()));
// 4. 如何获取数组的Stream流?
String[] names2 = {"张翠山", "东方不败", "唐大山", "独孤求败"};
Stream<String> s1 = Arrays.stream(names2);
Stream<String> s2 = Stream.of(names2);
}
}
标签:Stream,Java,进阶,stream,map,util,names,import
From: https://blog.csdn.net/chang_chunhua/article/details/143269040