0% found this document useful (0 votes)
6 views2 pages

4

Java 8 Programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

4

Java 8 Programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

To find duplicate elements in an array using Java 8 features, you can utilize a Stream with methods

like groupBy, filter, and collect. The idea is to count the occurrences of each element and then
identify which elements appear more than once.

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.function.Function;

import java.util.stream.Collectors;

public class FindDuplicates {

public static void main(String[] args) {

// Example array

int[] numbers = {1, 2, 3, 4, 5, 3, 2, 6, 7, 8, 1};

// Convert the array to a List of Integers (boxing)

List<Integer> numberList = Arrays.stream(numbers) // Convert the array to an IntStream

.boxed() // Box primitive int to Integer

.collect(Collectors.toList()); // Collect into a List<Integer>

// Find duplicates using Java 8 Stream API

Map<Integer, Long> elementCounts = numberList.stream()

.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));

// Filter elements that have a count greater than 1 (i.e., duplicates)

elementCounts.entrySet().stream()

.filter(entry -> entry.getValue() > 1)

.forEach(entry -> System.out.println("Duplicate element: " + entry.getKey() + " appears "


+ entry.getValue() + " times"));

}
Explanation:

1. Convert the Array to a List:

o Arrays.stream(numbers) creates an IntStream from the numbers array.

o .boxed() converts the IntStream to a Stream<Integer> (boxed primitive types).

o .collect(Collectors.toList()) collects the stream into a List<Integer>.

2. Grouping and Counting Elements:

o Collectors.groupingBy(Function.identity(), Collectors.counting()) groups the elements


by their value and counts how many times each element appears.

o This results in a Map<Integer, Long> where the key is the element and the value is
the count of its occurrences.

3. Filtering and Printing Duplicates:

o .filter(entry -> entry.getValue() > 1) filters out the entries where the count is greater
than 1 (i.e., duplicates).

o .forEach(entry -> System.out.println(...)) prints the duplicate elements and how


many times they appear.

You might also like