1.
collect(toList())
方法由Stream
里的值生成一个列表,是一个及早求值操作。
List<String> collected = Stream.of("a", "b", "c")
.collect(Collectors.toList());
collected.forEach(System.out::println);
2.
map
操作就可以使用该函数,将一个流中的值转换成一个新的流
List<String> collected = Stream.of("a", "b", "hello")
.map(string -> string.toUpperCase())➊
.collect(Collectors.toList());
collected.forEach(System.out::println);
传给map
➊的Lambda表达式只接受一个String
类型的参数,返回一个新的String
。参数和返回值不必属于同一种类型,但是Lambda表达式必须是Function
接口的一个实例,Function
接口是只包含一个参数的普通函数接口。
3.
遍历数据并检查其中的元素时,可尝试使用Stream
中提供的新方法filter
.
List<String> stringArrayList =
asList("1q234","1q342","1q2334","1q434","q34","324","q3224","22q34","22q34");
System.out.println("含有q的有:" + String.valueOf(stringArrayList.stream()
.filter(string -> {
System.out.println(string);
return string.contains("q");
})
.count()) + "个");
4.
flatMap
方法可用Stream
替换值,然后将多个Stream连接成一个Stream
List<Integer> together = Stream.of(asList(1, 2), asList(3, 4))
.flatMap(Collection::stream)
.collect(toList());
together.forEach(System.out::println);
5.
max
和min
List<String> stringList = asList("1", "22", "333", "4444", "55555");
String s = stringList.stream()
.min(Comparator.comparing(string -> string.length()))
.get();
System.out.println("-------min-----");
System.out.println(s);
List<String> stringList = asList("1", "22", "333", "4444", "55555");
String s = stringList.stream()
.max(Comparator.comparing(string -> string.length()))
.get();
System.out.println("-------max-----");
System.out.println(s);