To find duplicate elements in a list in Java, you can use the stream()
method to create a stream of the elements, and then use the collect()
method to group the elements by value and count the number of occurrences of each value.
Here's an example of how to do it:
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b", "c", "a", "b", "d", "e", "f", "c"); // Find the duplicate elements in the list Map<String, Long> duplicates = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(entry -> entry.getValue() > 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // Print the duplicate elements System.out.println(duplicates); // prints "{a=2, b=2, c=2}" } }
This code creates a list of strings and then uses the collect()
method to group the elements by value and count the number of occurrences of each value. The resulting map is then filtered to remove all entries with a count of 1, and the resulting map is printed.
Note that this approach only works if the elements of the list implement the equals()
and hashCode()
methods correctly. If you are working with a custom type, you may need to override these methods in order for the grouping and filtering to work properly.
You can use a similar approach to find duplicate elements in a list of any type of data, as long as you use the appropriate stream and collect methods.