简体   繁体   English

不区分大小写的排序集 - 使用不同的大小写保持相同的字符串

[英]Case-insensitive sorted Set - keep same string with different case

Today I have a case-insensitive sorted Set like: 今天我有一个不区分大小写的排序Set如:

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. 也就是说,我希望对集合的排序不区分大小写,但我希望能够在集合中使用具有不同情况的相同字符串(如“foo”和“FOO”),而不丢弃最后一个。

I know I could sort a List , but in my case I need a Set . 我知道我可以对List排序,但在我的情况下我需要一个Set

Is there a neat way of doing this in Java? 在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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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