189. Grouping

Let's assume that we have the following Melon class and List of Melon:

public class Melon {

enum Sugar {
LOW, MEDIUM, HIGH, UNKNOWN
}

private final String type;
private final int weight;
private final Sugar sugar;

// constructors, getters, setters, equals(),
// hashCode(), toString() omitted for brevity
}

List<Melon> melons = Arrays.asList(
new Melon("Crenshaw", 1200),
new Melon("Gac", 3000), new Melon("Hemi", 2600),
new Melon("Hemi", 1600), new Melon("Gac", 1200),
new Melon("Apollo", 2600), new Melon("Horned", 1700),
new Melon("Gac", 3000), new Melon("Hemi", 2600)
);

The Java Stream API exposes the same functionality as the SQL GROUP BY clause via Collectors.groupingBy().

While the SQL GROUP BY clause works on database tables, Collectors.groupingBy() works on elements of streams.

In other words, the groupingBy() methods are capable of grouping elements with certain distinguishing characteristics. Before streams and functional-style programming (Java 8), such tasks were applied to collections via a bunch of spaghetti code that was cumbersome, verbose, and error-prone. Starting with Java 8, we have grouping collectors.

Let's take a look at single-level grouping and multilevel grouping in the next section. We will start with single-level grouping.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.140