The groupingBy() function belongs to the Collectors class from java.util.stream package. It groups the elements based on a specified property, into a Stream. It is equivalent to the groupBy() operation in SQL.
Syntax
public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier)
Java Stream groupingBy() operation – examples
Example 1:
A program that will take a list of strings and group them by the length attribute:
class Test { public static void main(String[] args) { List<String> cities = new ArrayList<>(Arrays.asList("Paris", "Bern", "London", "Tokyo", "Boston")); Map<Integer, List<String>> resultMap = cities.stream() .collect(Collectors.groupingBy(String::length)); System.out.println(resultMap); } }
Output: {4=[Bern], 5=[Paris, Tokyo], 6=[London, Boston]}
Example 2:
Let’s write a program that will take a list of Users and group them by the membership type:
class Test { public static void main(String[] args) { Map<String, List<User>> resultMap = getAllUsers().stream() .collect(Collectors.groupingBy(User::getMembershipType)); System.out.println(resultMap); } private static List<User> getAllUsers() { List<User> users = new ArrayList<>(); users.add(new User("John", "john123", "premium", "5th Avenue")); users.add(new User("Megan", "meganusr", "gold", "New Light Street")); users.add(new User("Steve", "steve1234", "regular", "New Street Avenue")); users.add(new User("Melissa", "mell1", "premium", "Ser Kingston Street")); users.add(new User("Joan", "joan1234", "gold", "New Light Street")); return users; } } class User { private String name; private String username; private String membershipType; private String address; public User(String name, String username, String membershipType, String address) { this.name = name; this.username = username; this.membershipType = membershipType; this.address = address; } public String getMembershipType() { return membershipType; } @Override public String toString() { return "name: " + name + " ," + "username: " + username; } }
Output:
{ gold=[name: Megan ,username: meganusr, name: Joan ,username: joan1234], premium=[name: John ,username: john123, name: Melissa ,username: mell1], regular=[name: Steve ,username: steve1234] }
I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.