/** * Accumulates the elements of this stream into a {@code List}. The elements in * the list will be in this stream's encounter order, if one exists. The returned List * is unmodifiable; calls to any mutator method will always cause * {@code UnsupportedOperationException} to be thrown. There are no * guarantees on the implementation type or serializability of the returned List. * *
The returned instance may be value-based. * Callers should make no assumptions about the identity of the returned instances. * Identity-sensitive operations on these instances (reference equality ({@code ==}), * identity hash code, and synchronization) are unreliable and should be avoided. * *
This is a terminal operation. * * @apiNote If more control over the returned object is required, use * {@link Collectors#toCollection(Supplier)}. * * @implSpec The implementation in this interface returns a List produced as if by the following: *
* * @implNote Most instances of Stream will override this method and provide an implementation * that is highly optimized compared to the implementation in this interface. * * @return a List containing the stream elements * * @since 16 */ @SuppressWarnings("unchecked") default List toList() { return (List) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray()))); }
return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : new UnmodifiableList<>(list));
但其实也可以修改List的元素的某些属性,例如
List stringList = List.of("1", "2", "3"); List largeNumberList = stringList.stream().filter(number -> Long.parseLong(number) > 1).toList(); List largeNumberList2 = stringList.stream().filter(number -> Long.parseLong(number) > 1).collect(Collectors.toList()); largeNumberList.add("4"); // java.lang.UnsupportedOperationException largeNumberList2.add("4"); //success
// modify custom object attribute User userZhang = new User("ZhangSan"); User userLi = new User("LiSi"); List userList = List.of(userZhang, userLi); List filterList = userList.stream().filter(user -> "LiSi".equals(user.name)).toList();
User first = filterList.getFirst();//java 21 first.name = "WangWu"; filterList.forEach(u -> System.out.println(u.name)); //List.of返回的也是不能修改的List userList.forEach(u -> System.out.print(u.name));
/** * Returns a {@code Collector} that accumulates the input elements into a * new {@code List}. There are no guarantees on the type, mutability, * serializability, or thread-safety of the {@code List} returned; if more * control over the returned {@code List} is required, use {@link #toCollection(Supplier)}. * * @param the type of the input elements * @return a {@code Collector} which collects all the input elements into a * {@code List}, in encounter order */ public static Collector> toList() { return new CollectorImpl<>(ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, CH_ID); }
tips: List.of(),返回的也是不可修改的list, an unmodifiable list. 关于 Unmodifiable Lists 说明