Case insensitive collation Set - keep the same string with a different case
Today I have a case insensitive case Set
like:
Set<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set.add("foo");
set.add("FOO");
set.add("bar");
System.out.println(set.toString());
The result of this:
[bar, foo]
But I really wanted:
[bar, FOO, foo]
That is, I want the collation of the set to be case insensitive, but I want to have the same string with different cases (like "foo" and "FOO") in the set, without the last one being discarded.
I know I could sort List
, but in my case I need one Set
.
Is there an easy way to do this in Java?
+3
source to share
1 answer
You probably want to use a comparator that orders case insensitively and then uses a case sensitive case as a tiebreaker.
So something like:
Set<String> set = new TreeSet<>((a, b) -> {
int insensitive = String.CASE_INSENSITIVE_ORDER.compare(a, b);
return insensitive==0 ? a.compareTo(b) : insensitive;
});
+7
source to share