Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

java - 将集转换为列表而不创建新列表(Convert Set to List without creating new List)

I am using this code to convert a Set to a List :

(我正在使用此代码将Set转换为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?

(那可能吗?)

  ask by Muhammad Imran Tariq translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the List.addAll() method.

(您可以使用List.addAll()方法。)

It accepts a Collection as an argument, and your set is a Collection.

(它接受Collection作为参数,而您的集合就是Collection。)

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

EDIT: 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.

(很容易看出,如果要使用一个ListListMap作为值,为了拥有k个不同的值,您需要创建k个不同的列表。)
Thus: You cannot avoid creating these lists at all, the lists will have to be created.

(因此:您完全无法避免创建这些列表,必须创建列表。)

Possible work around:

(可能的解决方法:)
Declare your Map as a Map<String,Set> or Map<String,Collection> instead, and just insert your set.

(将Map声明为Map<String,Set>Map<String,Collection> ,然后插入您的地图集。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...