简体   繁体   中英

Case-insensitive sorted Set - keep same string with different case

Today I have a case-insensitive sorted 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 output of this is:

[bar, foo]

But what I really wanted was:

[bar, FOO, foo]

That is, I want the sorting of the set to be case-insensitive, but I want to be able to have same string with different cases (like "foo" and "FOO") in the set, without the last one being discarded.

I know I could sort a List , but in my case I need a Set .

Is there a neat way of doing this in Java?

You probably want to use a comparator that orders case insensitively then uses case sensitive ordering 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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM