Java 8 Stream Cheatsheet

Convert Array To Map

List<Employment> employmentList = ....;
Map<String, Employment> employments = employmentList.stream().collect(Collectors.toMap(Employment::getName, Function.identity()));

Merge Lists without duplications

List<CustomerLabel> merged = new ArrayList<>(
                Stream.of(currentLabels, toAddCustomerLabel)
                        .flatMap(List::stream)
                        .collect(Collectors.toMap(CustomerLabel::getId,
                                d -> d,
                                (CustomerLabel x, CustomerLabel y) -> x == null ? y : x))
                        .values());

Sum of a List

List<Sale> sales = ....
Double sum = sales.stream().map(Sale::getTotalDollars).reduce(0d, Double::sum);

Find Max Number

List<Double> numbers = ...
Double max = numbers.stream().max(Double::compareTo).orElse(null);

Find Min Number

List numbers = ...
Double min =numbers.stream().min(Double::compareTo).orElse(null);

(continue updating … )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s