I have two lists
List<String> names1;
List<String> names2;
I want a new list returned to me with values that exist in both lists. These values should not repeat as retainAll does.
This was my original approach:
return ListUtils.intersection(names1, names2);
And it works fine. But it is case-sensitive so AbC is not the same as abc. I need the comparison to be case insensitive. Is there another way to do this?
Put the contents of one list into a Set<String>
, lower-cased, say:
Set<String> lcNames2 =
names2.stream().map(String::toLowerCase).collect(Collectors.toSet());
Then:
List<String> intersection =
names2.stream()
.filter(n -> lcNames2.contains(n.toLowerCase())
.collect(Collectors.toList());
But note that the notion of intersection is rather ill-defined when you are not dealing with equality as the equivalence relation.
Lists.intersection
effectively treats the two lists as sets, since it will not add the same element twice.
But if you're not dealing with equals, what does it mean "not to add the same element twice"?
Or something else.
The exact solution depends upon your actual requirements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With