Convert Set to List without creating new List

2019-01-15 23:34发布

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?

12条回答
霸刀☆藐视天下
2楼-- · 2019-01-16 00:32

Use constructor to convert it:

List<?> list = new ArrayList<?>(set);
查看更多
ら.Afraid
3楼-- · 2019-01-16 00:32

the simplest solution

I wanted a very quick way to convert my set to List and return it, so in one line I did

 return new ArrayList<Long>(mySetVariable);
查看更多
乱世女痞
4楼-- · 2019-01-16 00:36

I found this working fine and useful to create a List from a Set.

ArrayList < String > L1 = new ArrayList < String > ();
L1.addAll(ActualMap.keySet());
for (String x: L1) {
    System.out.println(x.toString());
}
查看更多
神经病院院长
5楼-- · 2019-01-16 00:36

Also from Guava Collect library, you can use newArrayList(Collection):

Lists.newArrayList([your_set])

This would be very similar to the previous answer from amit, except that you do not need to declare (or instanciate) any list object.

查看更多
6楼-- · 2019-01-16 00:36

I would do :

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);
}
查看更多
何必那么认真
7楼-- · 2019-01-16 00:37

Recently I found this:

ArrayList<T> yourList = Collections.list(Collections.enumeration(yourSet<T>));
查看更多
登录 后发表回答