我正在使用这段代码将一个Set转换为一个List:

Map<String, List<String>> mainMap = new HashMap<>();

for (int i=0; i < something.size(); i++) {
  Set<String> set = getSet(...); //returns different result each time
  List<String> listOfNames = new ArrayList<>(set);
  mainMap.put(differentKeyName, listOfNames);
}

我希望避免在循环的每次迭代中创建一个新列表。这可能吗?


当前回答

我会这样做:

Map<String, Collection> mainMap = new HashMap<String, Collection>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  mainMap.put(differentKeyName,set);
}

其他回答

由于到目前为止还没有提到它,从Java 10开始,你可以使用新的copyOf工厂方法:

List.copyOf(set);

来自Javadoc:

按迭代顺序返回一个不可修改的List,其中包含给定Collection的元素。

注意,这将在底层创建一个新的列表(确切地说是ImmutableCollections$ListN)

在给定集合上调用Collection#toArray(),然后 将这些对象放入一个新数组中。

我们可以在Java 8中使用以下一行代码:

List<String> list = set.stream().collect(Collectors.toList());

这里有一个小例子:

public static void main(String[] args) {
        Set<String> set = new TreeSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        List<String> list = set.stream().collect(Collectors.toList());
}

最简单的解决方案

我想要一种非常快速的方法将我的set转换为List并返回它,所以在一行中我做到了

 return new ArrayList<Long>(mySetVariable);

您可以使用List.addAll()方法。它接受一个集合作为参数,您的集合就是一个集合。

List<String> mainList = new ArrayList<String>();
mainList.addAll(set);

编辑:作为对问题编辑的回应。 很容易看出,如果您想要有一个带有列表作为值的Map,为了有k个不同的值,您需要创建k个不同的列表。 因此:您根本无法避免创建这些列表,必须创建这些列表。

可能的解决方法: 声明你的Map为Map<String,Set>或Map<String,Collection>,然后插入你的Set。

我会这样做:

Map<String, Collection> mainMap = new HashMap<String, Collection>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  mainMap.put(differentKeyName,set);
}