Java 8 count duplicates in List

1. Overview

In this short tutorial, we'll look at some different ways to count the duplicated elements in an ArrayList.

1. Stream.distinct() – To Remove Duplicates

1.1. Remove Duplicate Strings

The distinct() method returns a Stream consisting of the distinct elements of the given stream. The object equality is checked according to the object’s equals() method.

List<String> list = Arrays.asList("A", "B", "C", "D", "A", "B", "C"); // Get list without duplicates List<String> distinctItems = list.stream() .distinct() .collect(Collectors.toList()); // Let's verify distinct elements System.out.println(distinctItems);

Program output:

[1, 2, 3, 4, 5, 6, 7, 8]

1.2. Remove Duplicate Custom Objects

The same syntax can be used to remove the duplicate objects from List. To do so, we need to be very careful about the object’s equals() method, because it will decide if an object is duplicate or unique.

Consider the below example where two Person instances are considered equal if both have the same id value.

public class Person { public Person(Integer id, String fname, String lname) { super(); this.id = id; this.fname = fname; this.lname = lname; } private Integer id; private String fname; private String lname; //Getters and Setters are hidden for brevity @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; return Objects.equals(id, other.id); } @Override public String toString() { return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]"; } }

Let us see an example of how we can remove duplicate Person objects from a List.

//Add some random persons Collection<Person> list = Arrays.asList(p1, p2, p3, p4, p5, p6); // Get distinct people by id List<Person> distinctElements = list.stream() .distinct() .collect( Collectors.toList() );

To find all unique objects using a different equality condition, we can take the help of the following distinctByKey() method. For example, we are finding all unique objects by Person’s full name.

//Add some random persons List<Person> list = Arrays.asList(p1, p2, p3, p4, p5, p6); // Get distinct people by full name List<Person> distinctPeople = list.stream() .filter( distinctByKey(p -> p.getFname() + " " + p.getLname()) ) .collect( Collectors.toList() ); //********The distinctByKey() method need to be created********** public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }

How to find duplicate elements in a Stream in Java

Given a stream containing some elements, the task is to find the duplicate elements in this stream in Java.

Examples:

Input: Stream = {5, 13, 4, 21, 13, 27, 2, 59, 59, 34}
Output: [59, 13]
Explanation:
The only duplicate elements in the given stream are 59 and 13.

Input: Stream = {5, 13, 4, 21, 27, 2, 59, 34}
Output: []
Explanation:
There are no duplicate elements in the given stream, hence the output is empty.

How to find duplicates in Java array?

In the first paragraph, I have given you a brief overview of three ways to find duplicate elements from Java array. Now, let's understand the logic behind each of those solutions in little more detail.

Solution 1 :

Our first solution is very simple. All we are doing here is to loop over an array and comparing each element to every other element. For doing this, we are using two loops, inner loop, and outer loop. We are also making sure that we are ignoring comparing of elements to itself by checking for i != j before printing duplicates. Since we are comparing every element to every other element, this solution has quadratic time complexity i.e. O(n^2). This solution has the worst complexity in all three solutions.
for (int i = 0; i < names.length; i++) { for (int j = i + 1 ; j < names.length; j++) { if (names[i].equals(names[j])) { // got the duplicate element } } }

This question is also very popular in programming interviews and if you are preparing for them, I also suggest you solve problems fromCracking the Coding Interview: 150 Programming Questions and Solutions. One of the best books to prepare for software developer interviews.

Java 8 count duplicates in List

Solution 2 :

The second solution is even simpler than this. All you need to know is that Set doesn't allow duplicates in Java. Which means if you have added an element into Set and trying to insert duplicate element again, it will not be allowed. In Java, you can use the HashSet class to solve this problem. Just loop over array elements, insert them into HashSet using add() method, and check the return value.

If add() returns false it means that element is not allowed in the Set and that is your duplicate. Here is the code sample to do this :

for (String name : names) { if (set.add(name) == false) { // your duplicate element } }
The complexity of this solution is O(n) because you are only going through the array one time, but it also has a space complexity of O(n) because of the HashSet data structure, which contains your unique elements. So if an array contains 1 million elements, in the worst case you would need a HashSet to store those 1 million elements.


Solution 3 :

Our third solution takes advantage of another useful data structure, hash table. All you need to do is loop through the array using enhanced for loop and insert each element and its count into hash table. You can use HashMap class of JDK to solve this problem. It is the general purpose hash table implementation in Java. In order to build table, you check if hash table contains the elements or not, if it is then increment the count otherwise insert element with count 1. Once you have this table ready, you can iterate over hashtable and print all those keys which has values greater than one. These are your duplicate elements. This is in fact a very good solution because you can extend it to found count of duplicates as well. If you remember, I have used this approach tofind duplicate characters in Stringearlier. Here is how you code will look like :
// build hash table with count for (String name : names) { Integer count = nameAndCount.get(name); if (count == null) { nameAndCount.put(name, 1); } else { nameAndCount.put(name, ++count); } } // Print duplicate elements from array in Java Set<Entry<String, Integer>> entrySet = nameAndCount.entrySet(); for (Entry<String, Integer> entry : entrySet) { if (entry.getValue() > 1) { System.out.printf("duplicate element '%s' and count '%d' :", entry.getKey(), entry.getValue()); } } Time complexity of this solution is O(2n) because we are iterating over array twice and space complexity is same as previous solution O(n). In worst case you would need a hash table with size of array itself.

Java 8 count duplicates in List




“find duplicate values in list java 8” Code Answer


java find duplicate element in list

java by Glamorous Gaur on Nov 14 2020 Comment

0

Add a Grepper Answer


  • java array check duplicates
  • java 8 retrieve all list from object into single list and ignore duplicates
  • java find duplicates in array
  • efficient generic duplicate finding class java
  • check if all values are same in list java
  • Find out duplicate number between 1 to n numbers in java
  • Java array repeating
  • find duplicate value in array java
  • find duplicate value in array using java

  • get duplicates from list java
  • java 8 get duplicates in list
  • java find duplicates in list
  • how to find duplicates in arraylist java
  • how to find duplicate elements in an array in java
  • arraylist find duplicates java
  • duplicate values list java
  • duplicate list java
  • check duplicates in list java
  • java duplicate list
  • check for duplicates in array list java
  • find duplicate name from a list java
  • check if there are duplicates in list java
  • java list find repeated elements
  • get repeated elements in list in java
  • how to check duplication from a list in java
  • how to find the duplicate in arraylist java
  • java list duplicate
  • java can list have duplicate value
  • how to find duplicates values + arraylist<> adnroid java
  • how to print duplicate elements in arraylist in java
  • how to find duplicate elements in array list in java
  • can list in java contain duplicate elements
  • get duplicate in the list java
  • how to find duplicate elements in arraylist in java 8
  • check if a list contains duplicates java
  • check the duplicate elements in arraylist in java
  • count duplicate elements in arraylist java
  • how to duplicate a value in a arraylist
  • find number of duplicates in list java
  • how to check duplicate name insert in a list in java
  • java list duplicates
  • duplicate java list
  • java check duplicate list
  • duplicate a list java
  • find the duplicate number in arraylist
  • java search for duplicates in a arraylist
  • get duplicates in list java
  • java duplicate list elements
  • elements are repeating in list java
  • java check list for duplicates
  • how to find which elements in a list have duplicates java
  • java duplicate elements in list
  • get duplicate values in list java
  • find duplicate lists java
  • how to identify duplicates in list java
  • how to get duplicates in arraylist java
  • how do you find duplicates in a list in java?
  • check for duplicate values in a list java
  • check for duplilcates in arraylist java
  • java find duplicates in list set
  • can java list contain duplicates
  • program to find duplicate elements in array using list java
  • find duplicate count in list java
  • java find duplicates in list of integer
  • find if repeating element in list java
  • how to find duplicate in list java
  • find the same string in a list in java
  • java 8 find duplicates in list of strings
  • how to get duplicates elements in list in java stream
  • find the repeated element in an list java 8
  • how to find out how many duplicates in list java
  • get duplicate values from two list java
  • find duplicate element in array in java
  • java find most duplicates in list
  • java 8 find duplicate string in list
  • does java list have duplicates
  • java duplicate list
  • how to find duplicate values in arraylist in java
  • duplicate values inside list java
  • find duplicate in list java
  • find duplicate elements in array in java
  • duplicate list in java
  • how to check duplicate in list java
  • how to check a list for duplicates in java
  • check for duplicates in an arraylist java
  • list duplicates java
  • java count duplicates in list
  • get duplicate string in list java
  • how to find duplicate elements in an arraylist java
  • count all duplicates in list java
  • how to find duplicate values in list in java
  • how to find duplicate elements in list java
  • duplicates in list java
  • can list have duplicates in java
  • arraylist java find duplicates
  • how to find duplicates values + arraylist<string> adnroid java
  • java how to get not duplicates value in list
  • how to find the duplicate values in arraylist in java
  • java can list have duplicates in java
  • best way to find duplicates in list java
  • count the duplicate elements in arraylist in java
  • find duplicate array list java
  • check duplicate entries in list java
  • how to find duplicate from two list in java
  • hwo to find the duplicate strings in array list in java
  • count duplicates in list java
  • how to find duplicate values in java in an arraylist
  • how to duplicate the list in java
  • to find duplicate elements in an array in java
  • can you duplicate in a list in java
  • how to count duplicates in arraylist java
  • list java duplicate elements
  • java find duplicate element
  • how to not display duplicates from a list java
  • how to duplicate list in java
  • check if list contains duplicates in java
  • how to find the duplicate elements in an arraylist
  • list find duplicates java
  • java list get duplicate values
  • best way to check for duplicates in list java
  • java can list have duplicates
  • how to check repeated element in list java
  • find duplicates in a list java
  • list can allows duplicate values yes or not
  • how to check for duplicates in different lists java
  • java detect duplicates in arraylist
  • java check if there are duplicates in list
  • get repeated elements in lis in java
  • find the list that contains duplicated adjacent elements java
  • duplicate element in arraylist java
  • how many duplicate elements can be added in a list java
  • java find duplicates from two lists
  • how to find duplicate from list in java
  • list in java with repeated value
  • how to print duplicates in a list java
  • how to find duplicates in list in java stream
  • how many duplicate elements in a list java
  • how to chech list for specific duplicate in java
  • how to check if there are duplicates in a list java
  • java list can i have duplicates
  • find duplicate elements in array using arraylist java
  • how to check duplicate value in list in java
  • count duplicate values in list java
  • duplicate value from list java
  • find duplicates in arraylist java
  • duplicate values in list java
  • java arraylist find duplicates
  • java get duplicates in list
  • find duplicates in the list java using stream
  • find duplicate values in list java 8
  • java list check for repeats
  • how to find duplicate values in arraylist in java given the array
  • how to find duplicate elements in arraylist
  • how to find duplicate items in arraylist in java
  • check duplicate in list java
  • java check for duplicates in list
  • find same numbers in a list in java
  • in java collection sets store a group of duplicate entries in excel
  • java find duplicates in list
  • how to find duplicate values in arraylist
  • find duplicates elements in an arraylist using contains() in java
  • find duplicate using list java
  • find duplicates elements using contains in arraylist java
  • how to find the repeated elements in an arraylist
  • how to check the duplicate object in a list in java
  • find duplicate elements in arraylist in java
  • find duplicates in arraylist
  • find duplicate elemets in array java
  • count duplicate elements in list java
  • how to get duplicate values from list in java
  • java check if an element is duplicates in list
  • how to print duplicate element from list in java
  • java check an element is duplicate value in list
  • java count duplicates in two lists
  • find duplicate in a list in java 11
  • java list can have duplicates?
  • check if there is duplicate in list java
  • list with duplicates java
  • count duplicate integer in list java
  • how to find duplicates in an arraylist java
  • find the duplicates in list and print in java
  • java duplicates in list
  • java find duplicate element in list
  • can we have duplicate value in list in java
  • java list duplicate values
  • check list for duplicates java
  • check for duplicates in list java
  • how to find duplicates in list java 8
  • find the duplicate elements from array in java
  • check for duplicate in arraylist java
  • get duplicates in arraylist java
  • java find first double element in list
  • how to check number of identica; elements ion java string
  • list contains duplicate values in java
  • how to manually find duplicates in a list java
  • if duplicate values exists what is returned java'
  • how to find duplicate items in arraylist java
  • find duplicate in arraylist java
  • java find same elements in list
  • list duplicate elements java
  • java stream find duplicates in list
  • java list find duplicates
  • how to get duplicates in list in java stream
  • find all duplicates in list of integers java
  • count the duplicate elements in list in java
  • java if value duplicates in list
  • how to check if there are duplicates in a list in java
  • java check duplicate list of list
  • find duplicates values in list in java
  • find out duplicate element in array java
  • java 8 check duplicates in list