问题描述
我正在使用此代码将Set
转换为List
:
I am using this code to convert a Set
to a List
:
Map<String, List> mainMap = new HashMap<String, List>();
for(int i=0; i<something.size(); i++){
Set set = getSet(...); //returns different result each time
List listOfNames = new ArrayList(set);
mainMap.put(differentKeyName,listOfNames);
}
我想避免在循环的每次迭代中创建一个新列表.有可能吗?
I want to avoid creating a new list in each iteration of the loop. Is that possible?
推荐答案
您可以使用 List.addAll()方法.它接受一个Collection作为参数,而您的集合就是一个Collection.
You can use the List.addAll() method. It accepts a Collection as an argument, and your set is a Collection.
List<String> mainList = new ArrayList<String>();
mainList.addAll(set);
编辑:对问题的编辑进行回复.
很容易看出,如果要使用List
作为值的Map
,要具有k个不同的值,则需要创建k个不同的列表.
因此:您无法避免完全创建这些列表,必须创建列表.
as respond to the edit of the question.
It is easy to see that if you want to have a Map
with List
s as values, in order to have k different values, you need to create k different lists.
Thus: You cannot avoid creating these lists at all, the lists will have to be created.
可能的解决方法:
相反,将您的Map
声明为Map<String,Set>
或Map<String,Collection>
,只需插入您的设置即可.
Possible work around:
Declare your Map
as a Map<String,Set>
or Map<String,Collection>
instead, and just insert your set.
这篇关于将集转换为列表而不创建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!