How to copy a card to another card

I have two cards

Map<String, List<String>> map = new HashMap<>();
Map<Integer, List<String>> newMap = new TreeMap<>();

      

in map

my key is the age of the user. I want to group them by age and copy to newMap

. For example: all ages between ages 10 and 1 group (and to copy all values ​​into one list), and all ages over 10 and under 20 to another, etc. here is what i tried to do

for (int m = 10; m <= 80; m += 10) {                            
    for (String key : map.keySet()) {
        List<String> value = new ArrayList<>();
        int age = Integer.parseInt(key);
        if (age <= m) {                     
            if ((value = newMap.get(m)) != null) {
                value.addAll(map.get(key));
                newMap.put(m, value);                           
            } else {
                newMap.put(m, value);

            }
        } else continue;            
    }
}

      

But I have age as key and zero as values [10 = null; 30 = null 20 = null; ]

+3


source to share


2 answers


Why not just go over it entrySet()

?



for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    // Since integer division is used, we'll lose the "ones" digit
    Integer newKey = Integer.parseInt(entry.getKey()) / 10 * 10;

    List<String> value = newMap.get(newKey) {
    if (value == null) {
        value = new LinkedList<>();
        newMap.put(newKey, value);
    }
    value.addAll(entry.getValue());
}

      

+1


source


I think Mureinik is better, but give something more similar to what you originally wrote:



for (int m = 10; m <= 80; m += 10) {
    List<String> value = new ArrayList<>();

    for (String key : map.keySet()) {
        int age = Integer.parseInt(key);

        if (age < m && age >= m - 9) {
            value.addAll(map.get(key));
        }
    }

    newMap.put(m, value);
}

      

+1


source







All Articles