将Set <String>转换为List <String>的最简洁方法

Jac*_*ine 198 java collections list set jdk1.6

我目前正在这样做:

Set<String> setOfTopicAuthors = ....

List<String> list = Arrays.asList( 
    setOfTopicAuthors.toArray( new String[0] ) );
Run Code Online (Sandbox Code Playgroud)

你能打败这个吗?

Sch*_*jer 424

List<String> list = new ArrayList<String>(listOfTopicAuthors);
Run Code Online (Sandbox Code Playgroud)

  • 我相信在Java 7及更高版本中你可以省略`ArrayList`的类型参数:```List <String> l = new ArrayList <>(listOfTopicAuthors);```最简洁而不使用外部库? (2认同)

Ada*_*ski 89

List<String> l = new ArrayList<String>(listOfTopicAuthors);
Run Code Online (Sandbox Code Playgroud)

  • 比接受的答案更简洁.+1 (10认同)
  • 在接受答案的同一分钟回答并且没有获得信用.+1 (4认同)

i_a*_*ero 22

考虑到我们Set<String> stringSet可以使用以下内容:

Java 10(不可修改的列表)

List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());
Run Code Online (Sandbox Code Playgroud)

Java 8(可修改列表)

import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());
Run Code Online (Sandbox Code Playgroud)

根据方法的文档toList()

返回的List的类型,可变性,可序列化或线程安全性无法保证; 如果需要更多地控制返回的List,请使用toCollection(Supplier).

因此,如果我们需要特定的实现,例如ArrayList我们可以这样做:

List<String> stringList2 = stringSet.stream().
                              collect(toCollection(ArrayList::new));
Run Code Online (Sandbox Code Playgroud)

Java 8(不可修改的列表)

我们可以使用Collections::unmodifiableList方法并包装前面示例中返回的列表.我们也可以编写自己的自定义方法:

class ImmutableCollector {
    public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
            return Collector.of( supplier, List::add, (left, right) -> {
                        left.addAll(right);
                        return left;
                    }, Collections::unmodifiableList);
        }
}
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

List<String> stringList3 = stringSet.stream()
             .collect(ImmutableCollector.toImmutableList(ArrayList::new)); 
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用collectingAndThen允许在返回结果之前完成一些最终转换的方法:

    List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
      toCollection(ArrayList::new),Collections::unmodifiableList));
Run Code Online (Sandbox Code Playgroud)

点要注意的是,该方法Collections::unmodifiableList返回指定列表的不可修改视图,按照文档.不可修改的视图集合是一个不可修改的集合,也是一个支持集合的视图.请注意,可能仍然可以对支持集合进行更改,如果它们发生,则通过不可修改的视图可以看到它们.但是collector方法Collectors.unmodifiableListJava 10中返回真正的不可变列表.


Pra*_*ena 13

尝试此设置:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 
Run Code Online (Sandbox Code Playgroud)

试试这个地图:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());
Run Code Online (Sandbox Code Playgroud)