To filter a list in Java to remove duplicate entries, you can use the distinct()
method of the Stream
class. Here's an example of how to do it:
import java.util.Arrays; import java.util.List; 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"); // Filter the list to remove duplicate entries List<String> filteredList = list.stream() .distinct() .collect(Collectors.toList()); // Print the filtered list System.out.println(filteredList); } }
This code creates a list of strings and then uses the distinct()
method to remove all duplicate entries. The collect()
method is used to collect the remaining elements into a new list.
Note that the distinct()
method 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 distinct()
method to work properly.
You can use a similar approach to filter a list of any type of data. Just make sure to use the appropriate Stream
and the appropriate method to collect the elements into a list.