Convert Set to List without creating new List

前端 未结 15 930
鱼传尺愫
鱼传尺愫 2020-12-07 06:43

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

Map> mainMap = new HashMap<>();

for (int i         


        
15条回答
  •  死守一世寂寞
    2020-12-07 07:23

    You convert Set to List without adding ordering information (like sorting) just to store it in the map.

    Because Set is unordered and no ordering information is added, List should not be used, as it will contain randomly ordered data and all it's methods that are related to ordered data will be ambiguous.

    You should use Collection interface instead, that accepts both Set and List in the map. This way, no additional memory is required as you use polymorphism instead of copying data.

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

    Disclaimer: my edit to a similar answer was rejected so I added my own answer with additional information

提交回复
热议问题