Reputation: 59
So i have a Armstrong List = " [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407] "
And i am trying to put it in a Map like this " {1=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3=[153, 370, 371, 407]} "
My Code:
public static Map<Integer, List<Integer>> groupByLength(List<Integer> list){
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
List<Integer> neu = new ArrayList<Integer>();
String s = "";
for(int i = 0; i < list.size(); i++) {
s = list.get(i) + "";
if(map.containsKey(s.length())) {
neu.add(list.get(i));
}
else {
map.put(s.length(), neu);
neu.clear();
}
s = "";
}
return map;
}
My problem is, if i change the list (neu), the list in the map will change too
Output
{1=[370, 371, 407], 3=[370, 371, 407]}
Upvotes: 0
Views: 171
Reputation: 2981
Your map has Key-Value pairs and you need to be adding elements to the list that is the Value. If your map doesn't have the Key-Value pair, then you need to instantiate a new list, add a value to it and put
it in the map. The method getOrDefault()
is very helpful in this case because it lets you get the Value list or create a new one into which you can add values:
public static Map<Integer, List<Integer>> groupByLength(List<Integer> list){
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
for(Integer el : list) {
int key = el.toString().length();
List<Integer> value = map.getOrDefault(key, new ArrayList<Integer>());
value.add(el);
map.put(key, value);
}
return map;
}
Edit: A "fancier" at first sight but quite clever optimization as suggested by Pshemo. You can find the same example in the documentation for computeIfAbsent()
public static Map<Integer, List<Integer>> groupByLength(List<Integer> list){
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
for(Integer el : list) {
int key = el.toString().length();
map.computeIfAbsent(key, k -> new ArrayList<>()).add(el);
}
return map;
}
Upvotes: 3