Most concise way to convert a Set to a List

后端 未结 6 1360
失恋的感觉
失恋的感觉 2020-12-07 12:00

For example, I am currently doing this:

Set setOfTopicAuthors = ....

List list = Arrays.asList( 
    setOfTopicAuthors.toArray(          


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 12:39

    Considering that we have Set stringSet we can use following:

    Java 10 (Unmodifiable list)

    List strList = stringSet.stream().collect(Collectors.toUnmodifiableList());
    

    Java 8 (Modifiable Lists)

    import static java.util.stream.Collectors.*;
    List stringList1 = stringSet.stream().collect(toList());
    

    As per the doc for the method toList()

    There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

    So if we need a specific implementation e.g. ArrayList we can get it this way:

    List stringList2 = stringSet.stream().
                                  collect(toCollection(ArrayList::new));
    

    Java 8 (Unmodifiable Lists)

    We can make use of Collections::unmodifiableList method and wrap the list returned in previous examples. We can also write our own custom method as:

    class ImmutableCollector {
        public static  Collector, List> toImmutableList(Supplier> supplier) {
                return Collector.of( supplier, List::add, (left, right) -> {
                            left.addAll(right);
                            return left;
                        }, Collections::unmodifiableList);
            }
    }
    

    And then use it as:

    List stringList3 = stringSet.stream()
                 .collect(ImmutableCollector.toImmutableList(ArrayList::new)); 
    

    Another possibility is to make use of collectingAndThen method which allows some final transformation to be done before returning result:

        List stringList4 = stringSet.stream().collect(collectingAndThen(
          toCollection(ArrayList::new),Collections::unmodifiableList));
    

    One point to note is that the method Collections::unmodifiableList returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList returns truly immutable list in Java 10.

提交回复
热议问题