streams的三个步骤
- 创建stream
- 中间操作
- 终止操作(终端操作)
筛选与切片
- filter—接受Lambda,从流中排出某些元素
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().filter(e -> "aaa".equals(e)).forEach(e -> System.out.print(e + " "));
outPut : aaa aaa
- limit—截断流,使其元素不能超过给定数量
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().filter(e -> "aaa".equals(e)).limit(1).forEach(e -> System.out.print(e + " "));
outPut : aaa
- skip(n)—跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().skip(2).forEach(e -> System.out.print(e + " "));
outPut : ddd aaa ccc ddd eee
- distinct—筛选,通过流所生成元素的hashCode()和equals()去除重复元素
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().distinct().forEach(e -> System.out.print(e + " "));
outPut : bbb aaa ddd ccc eee
映射
- map–接受映射Lambda,将元素转换成其他形式或提取信息。接收另一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
public void mapTest() {
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().map(e -> e.toUpperCase()).forEach(e -> System.out.print(e + " "));
}
outOut : BBB AAA DDD AAA CCC DDD EEE
- flatMap–接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流
@Test
public void mapTest() {
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
Stream<Stream<Character>> stream = list.stream().limit(2).map(e -> filterCharacter(e));
System.out.print("map:");
//返回的stream里的每个值都是流
stream.forEach(sm -> {
sm.forEach(e -> {System.out.print(e + " ");});
});
System.out.println();
System.out.print("flarMap:");
//返回的流直接连接成一个流
Stream<Character> stream2 = list.stream().limit(2).flatMap(e -> filterCharacter(e));
stream2.forEach(e -> System.out.print(e + " "));
}
public static Stream<Character> filterCharacter(String str) {
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()) {
list.add(ch);
}
return list.stream();
}
outPut : map:b b b a a a
flarMap:b b b a a a
排序
- sorted()–自然排序
List<Integer> list = Arrays.asList(5, 3, 4, 1, 2);
list.stream().sorted().forEach(e -> System.out.print(e + " "));
outPut : 1 2 3 4 5
- sorted(comparator com)–定制排序
List<Integer> list = Arrays.asList(5, 3, 4, 1, 2);
list.stream().sorted((x, y) -> y.compareTo(x)).forEach(e -> System.out.print(e + " "));
outPut : 5 4 3 2 1