Java8 Stream流
Java8关于map和flatMap的代码片段思考
Java8初体验(二)Stream语法详解
distinct()
/*
返回一个流包含不同的元素(根据equals方法判断,null值并不会报空指针异常,会保留一个null)。
对于有序的流保证稳定性,保留最先出现的元素,对于无序的流不保证稳定性。
*/
/**
* Returns a stream consisting of the distinct elements (according to
* {@link Object#equals(Object)}) of this stream.
*
* <p>For ordered streams, the selection of distinct elements is stable
* (for duplicated elements, the element appearing first in the encounter
* order is preserved.) For unordered streams, no stability guarantees
* are made.
*
* <p>This is a <a href="package-summary.html#StreamOps">stateful
* intermediate operation</a>.
*
* @apiNote
* Preserving stability for {@code distinct()} in parallel pipelines is
* relatively expensive (requires that the operation act as a full barrier,
* with substantial buffering overhead), and stability is often not needed.
* Using an unordered stream source (such as {@link #generate(Supplier)})
* or removing the ordering constraint with {@link #unordered()} may result
* in significantly more efficient execution for {@code distinct()} in parallel
* pipelines, if the semantics of your situation permit. If consistency
* with encounter order is required, and you are experiencing poor performance
* or memory utilization with {@code distinct()} in parallel pipelines,
* switching to sequential execution with {@link #sequential()} may improve
* performance.
*
* @return the new stream
*/
Stream<T> distinct();
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(null, 1, 2, 2, 3, null);
List<Integer> result = integers.stream().distinct().collect(Collectors.toList());
//[null, 1, 2, 3] 并不会去除null值和报空指针异常。
System.out.println(result);
List<Integer> result2 = integers.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
//[1, 2, 3] 去重同时去除null值。
System.out.println(result2);
}
flatMap()
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
public static void main(String[] args) {
List<List<String>> lists = new ArrayList<>();
lists.add(Arrays.asList("tom1", "tom2"));
lists.add(Arrays.asList("java1", "java2"));
lists.add(Arrays.asList("web1", "web2"));
/*
将流中的每个元素转换为一个流,会得到多个流,然后将这些流合并成一个流,。
上面6个字符串被合并到一个流中
*/
lists.stream().flatMap(Collection::stream).forEach(System.out::println);
}