Java 8 – Find duplicate elements in a Stream

This article shows you three algorithms to find duplicate elements in a Stream. Set.add() Collectors.groupingBy Collections.frequency At the end of the article, we use the JMH benchmark to test which one is the fastest algorithm. 1. Filter & Set.add() The Set.add() returns false if the element was already in the set; let see the benchmark …

Read more

Java 8 – Stream Collectors groupingBy examples

In this article, we will show you how to use Java 8 Stream Collectors to group by, count, sum and sort a List. 1. Group By, Count and Sort 1.1 Group by a List and display the total count of it. Java8Example1.java package com.mkyong.java8; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public …

Read more

Java 8 – Convert List to Map

Few Java 8 examples to show you how to convert a List of objects into a Map, and how to handle the duplicated keys. Hosting.java package com.mkyong.java8 public class Hosting { private int Id; private String name; private long websites; public Hosting(int id, String name, long websites) { Id = id; this.name = name; this.websites …

Read more

Java 8 Streams filter examples

In this tutorial, we will show you few Java 8 examples to demonstrate the use of Streams filter(), collect(), findAny() and orElse() 1. Streams filter() and collect() 1.1 Before Java 8, filter a List like this : BeforeJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BeforeJava8 { public static void main(String[] args) …

Read more