Collectors.toUnmodifiableList in java-10

Eugene :

How do you create an Unmodifiable List/Set/Map with Collectors.toList/toSet/toMap, since toList (and the like) are document as :

There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned

Before java-10 you have to provide a Function with Collectors.collectingAndThen, for example:

 List<Integer> result = Arrays.asList(1, 2, 3, 4)
            .stream()
            .collect(Collectors.collectingAndThen(
                    Collectors.toList(),
                    x -> Collections.unmodifiableList(x)));
Eugene :

With Java 10, this is much easier and a lot more readable:

List<Integer> result = Arrays.asList(1, 2, 3, 4)
            .stream()
            .collect(Collectors.toUnmodifiableList());

Internally, it's the same thing as Collectors.collectingAndThen, but returns an instance of unmodifiable List that was added in Java 9.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433544&siteId=1