Skip to content

Instantly share code, notes, and snippets.

@vfarcic
Created November 2, 2014 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vfarcic/c1fe93571b520e03b558 to your computer and use it in GitHub Desktop.
Save vfarcic/c1fe93571b520e03b558 to your computer and use it in GitHub Desktop.
package com.technologyconversations.java8exercises.streams;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class Grouping {
public static Map<String, List<Person>> groupByNationality7(List<Person> people) {
Map<String, List<Person>> map = new HashMap<>();
for (Person person : people) {
if (!map.containsKey(person.getNationality())) {
map.put(person.getNationality(), new ArrayList<>());
}
map.get(person.getNationality()).add(person);
}
return map;
}
public static Map<String, List<Person>> groupByNationality(List<Person> people) {
return people.stream() // Convert collection to Stream
.collect(groupingBy(Person::getNationality)); // Group people by nationality
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment