In Java 8, all of your code can be written like this (like other great answers):
Map<Integer, List<Person>> myHashMap = new HashMap(); for (Person person : persons) { myHashMap.computeIfAbsent(age,age->new ArrayList<Person>()).add(person); }
But you can be even shorter using a stream that collects in a Map with Collectors.groupingBy() :
Map<Integer, List<Person>> myMap = persons.stream().collect(Collectors.groupingBy(Person:getAge));
As a side note, your actual Java 7 code can also be improved. Of course, not as much as with Java 8, but if you cannot use Java 8, this can be interesting.
In your actual code, this is duplicated:
personsOfSameAge.add(person);
And you use two conditional statements ( if and else ), while only if will be enough if you first handle the special case: there is no value in Map . Here is a modified version:
Map<Integer, List<Person>> myHashMap = new HashMap<>(); for (Person person : persons) { int age = person.getAge(); List<Person> personsOfSameAge = myHashMap.get(age); if (personsOfSameAge == null) { personsOfSameAge = new ArrayList(); myHashMap.put(age, personsOfSameAge); } personsOfSameAge.add(person); }
davidxxx
source share