Java – a case insensitive sort set – maintains the same string in different cases

Today I have a case insensitive sort set, such as:

Set<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set.add("foo");
set.add("FOO");
set.add("bar");
System.out.println(set.toString());

This output is:

[bar,foo]

But what I really want is:

[bar,FOO,foo]

That is, I want to sort the collection case insensitive, but I want to be able to use the same strings with different situations in the collection (such as "foo" and "foo") without discarding the last one

I know I can sort the list, but in my case, I need a set

Is there such a clever method in Java?

Solution

You may want to use a case insensitive comparator and then use case sensitive order as the winning game

So it's similar to:

Set<String> set = new TreeSet<>((a,b) -> {
    int insensitive = String.CASE_INSENSITIVE_ORDER.compare(a,b);
    return insensitive==0 ? a.compareTo(b) : insensitive;
});
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>