Tishy Tash
Tishy Tash

Reputation: 357

Check if any entry of first list is missing from second list

I have two lists of String objects. First list can have an object that can be splitted on basis of some delimiter. I want to get all those records of first list which are not present in second list.

List<String> list = Arrays.asList("A;H","B","C","D");
List collection = Arrays.asList("AH","B","D","E","F");
List<String> result = list.stream().filter(str -> !collection.contains(str)).collect(Collectors.toList());

The above code is partially correct according to my requirement. It outputs [A;H, C]. My requirement is it should only give output as C. Because if any of character or String object of "A;H" is present in second list. It should not be collected.

Upvotes: 0

Views: 473

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You can use a regular expression to eliminate the delimiting character and then compare the values for the existence. Here's how it looks.

private static final Pattern DELIMITER = Pattern.compile("\\W");

Set<String> set = new HashSet<>(collection);

List<String> nonExistingValues = list.stream()
    .map(s -> DELIMITER.splitAsStream(s).collect(Collectors.joining()))
    .filter(s -> !set.contains(s))
    .collect(Collectors.toList());

A much more compact approach which reuses the pattern as mentioned in the below comment would be,

List<String> nonExistingValues = list.stream()
    .map(s -> DELIMITER.matcher(s).replaceAll(""))
    .filter(s -> !set.contains(s))
    .collect(Collectors.toList());

Upvotes: 3

Related Questions