Remove duplicated elements from a collection

By | July 26, 2016 | 152 Views

1. Using LinkedHashSet from a given list

List<String> names = Arrays.asList("Jack","Peter","Jack", "Jame");
names = new ArrayList<>(new LinkedHashSet<>(names));
System.out.println(names);

Remove duplicated elements by using LinkedHashSet because it contains unique element and in the same order as the List
Output in console:

[Jack, Peter, Jame]

2. Lambda Stream on arbitrary key

public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
		Map<Object, String> seen = new ConcurrentHashMap<>();
		return t -> seen.put(keyExtractor.apply(t), "") == null;
	}
public static void main(String[] args) {
		List<Module> saqModules = Arrays.asList(
				new Module("code1", "name1", 1), 
				new Module("code1", "name2", 2),
				new Module("code2", "name3", 3), 
				new Module("code3", "name4", 4));

		List<ModuleFilterDTO> moduleFilterDTOs = saqModules.stream()
				.filter(distinctByKey(m -> m.getModuleCode()))
				.map(m -> new ModuleFilterDTO(m.getModuleCode(), m.getModuleName()))
				.collect(Collectors.toList());

		moduleFilterDTOs.forEach(item -> System.out.println(item.toString()));

	}

Output in console:

code1 name
code2 name
code3 name

Leave a Reply

Your email address will not be published. Required fields are marked *