187. Joining the results of a stream

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

public class Melon {

private String type;
private int weight;

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

Let's also assume that we have the List of Melon:

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

In the previous problem, we talked about the Stream API that's built into Collectors. In this category, we also have Collectors.joining(). The goal of these collectors is to concatenate the elements of a stream into a String in the encounter order. Optionally, these collectors can use a delimiter, a prefix, and a suffix, and so the most comprehensive joining() flavor is String joining​(CharSequence delimiter, CharSequence prefix, CharSequence suffix).

But if all we want is to concatenate the names of melons without a delimiter, then this is the way to go (just for fun, let's sort and remove the duplicates as well):

String melonNames = melons.stream()
.map(Melon::getType)
.distinct()
.sorted()
.collect(Collectors.joining());

We will receive the following output:

ApolloCantaloupeCrenshawGacHemiHorned

A nicer solution consists of adding a delimiter, for example, a comma and a space:

String melonNames = melons.stream()
...
.collect(Collectors.joining(", "));

We will receive the following output:

Apollo, Cantaloupe, Crenshaw, Gac, Hemi, Horned

We can also enrich the output with a prefix and suffix:

String melonNames = melons.stream()
...
.collect(Collectors.joining(", ",
"Available melons: ", " Thank you!"));

We will receive the following output:

Available melons: Apollo, Cantaloupe, Crenshaw, Gac, Hemi, Horned Thank you!
..................Content has been hidden....................

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