Stream流

获取流

集合 ->stream .stream()

List list = new ArrayList<>();
Stream stream1 = list.stream();

Set set = new HashSet<>();
Stream stream2 = set.stream();

Vector vector = new Vector<>();
Stream stream3 = vector.stream();

Map -> stream

需要将key和value拆开变成流,或者先变成entry来变成流

Map map = new HashMap<>();
// ...
Stream keyStream = map.keySet().stream();
Stream valueStream = map.values().stream();
Stream> entryStream = map.entrySet().stream();
}

数组 -> stream stream.of(array)

String[] array = { "张无忌", "张翠山", "张三丰", "张一元" };
Stream stream = Stream.of(array);

stream常用方法

foreach

Stream stream = Stream.of("张无忌", "张三丰", "周芷若");
stream.forEach(name‐> System.out.println(name));

过滤filter

Stream original = Stream.of("张无忌", "张三丰", "周芷若");
Stream result = original.filter(s ‐> s.startsWith("张"))

映射map

Stream original = Stream.of("10", "12", "18");
Stream result = original.map(str‐>Integer.parseInt(str));

统计个数count

Stream original = Stream.of("张无忌", "张三丰", "周芷若");
Stream result = original.filter(s ‐> s.startsWith("张"));
System.out.println(result.count()); // 2

取用前几个limit

如果参数大于长度,不进行操作

Stream original = Stream.of("张无忌", "张三丰", "周芷若");
Stream result = original.limit(2);
System.out.println(result.count()); // 2

跳过前几个skip

如果参数大于长度,返回一个空的流

Stream original = Stream.of("张无忌", "张三丰", "周芷若");
Stream result = original.skip(2);
System.out.println(result.count()); // 1

流拼接concat

Stream streamA = Stream.of("张无忌");
Stream streamB = Stream.of("张翠山");
Stream result = Stream.concat(streamA, streamB);

你可能感兴趣的:(Stream流)