示例代码:
var newList = someCollection.stream()
.map(x -> mapX(x))
.filter(x -> filterX(x))
.toList();
// 对比
var oldList = someCollection.stream()
.map(x -> mapX(x))
.filter(x -> filterX(x))
.collect(Collectors.toList());
Stream.toList() 和 Stream.collect(Collectors.toList())的区别:
Stream.toList()
提供了一个不可变的List实现(类型为ImmutableCollections.ListN
)与List.of()
提供的类似,并与Stream.collect(Collections.toList())
提供的可变(可以更改和排序)ArrayList形成对比。
例如,
import java.util.stream.Stream;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Stream.of("Hello").toList();
System.out.println(list);
list.add("Hi");
}
}
输出:
[Hello]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
at Main.main(Main.java:8)
Stream.toList()成功返回一个包含空值的列表:
import java.util.stream.Stream;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Object> list = Stream.of(null, null).toList();
System.out.println(list);
}
}
输出:
[null, null]
List.of(null, null) 抛出NullPointerException:
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Object> list = List.of(null, null);
}
}
输出:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:208)
at java.base/java.util.ImmutableCollections$List12.<init>(ImmutableCollections.java:453)
at java.base/java.util.List.of(List.java:827)
at Main.main(Main.java:5)
Stream.collect(Collectors.toList()):可以修改,允许空值。
Stream.collect(collections . tounmodifiableelist()):不可以修改,不允许空值
Stream.toList():不可以修改,允许空值。