将集转换为列表而不创建新列表 [英] Convert Set to List without creating new List

查看:59
本文介绍了将集转换为列表而不创建新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码将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?

推荐答案

您可以使用

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 Lists 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.

这篇关于将集转换为列表而不创建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆