Monday, 30 March 2026

Find Duplicate in List of Integer using Java 8 Stream

package in.jk.array.basic.java8;


import java.util.Arrays;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.function.Function;

import java.util.stream.Collectors;


public class Java8 {

public static void main(String[] args) {

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);

Set<Integer> set = new HashSet<Integer>();

// Method 1

myList.stream().filter(n->!set.add(n))

.forEach(System.out::println);

//Method 2

Map<Integer,Long> result= myList.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))

.entrySet()

.stream()

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

.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

System.out.println(result);



}


}

No comments:

Post a Comment