Junior — Middle
What methods can be used to eliminate duplicate elements in a list?
sobes.tech AI
Answer from AI
To eliminate duplicate elements in a list in Java, several methods can be used:
- Using a Set — a set does not store duplicates, so you can create a HashSet from the list, and then convert it back to a list if needed:
List<String> list = Arrays.asList("a", "b", "a", "c");
Set<String> set = new HashSet<>(list);
List<String> uniqueList = new ArrayList<>(set);
- Using Stream API (Java 8+) with the
distinct()method:
List<String> list = Arrays.asList("a", "b", "a", "c");
List<String> uniqueList = list.stream()
.distinct()
.collect(Collectors.toList());
- Manual iteration with a check for element existence — less efficient, but sometimes used.
Most often, the Stream API method is preferred because it is concise and convenient.