java 在不区分大小写的情况下检查 ArrayList 是否包含某个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39992020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:50:13  来源:igfitidea点击:

Checking if an ArrayList contains a certain String while being case insensitive

javaarraylist

提问by Ragnar Johansen

How can i search through an ArrayList using the .contains method while being case insensitive? I've tried .containsIgnoreCase but found out that the IgnoreCase method only works for Strings.

如何在不区分大小写的情况下使用 .contains 方法搜索 ArrayList?我试过 .containsIgnoreCase 但发现 IgnoreCase 方法只适用于字符串。

Here's the method I'm trying to create:

这是我尝试创建的方法:

 private ArrayList<String> Ord = new ArrayList<String>(); 

 public void leggTilOrd(String ord){
     if (!Ord.contains(ord)){
         Ord.add(ord);
     }
 }

回答by Aaron Davis

You will need to iterate over the list and check each element. This is what is happening in the containsmethod. Since you are wanting to use the equalsIgnoreCasemethod instead of the equalsmethod for the String elements you are checking, you will need to do it explicitly. That can either be with a for-each loop or with a Stream (example below is with a Stream).

您将需要遍历列表并检查每个元素。这就是contains方法中发生的事情。由于您想要使用该equalsIgnoreCase方法而不是equals您正在检查的 String 元素的方法,因此您需要明确地执行此操作。这可以使用 for-each 循环或使用 Stream(下面的示例是使用 Stream)。

private final List<String> list = new ArrayList<>();

public void addIfNotPresent(String str) {
    if (list.stream().noneMatch(s -> s.equalsIgnoreCase(str))) {
        list.add(str);
    }
}

回答by Kris

If you are using Java7, simply override the contains() method,

如果您使用的是 Java7,只需覆盖 contains() 方法,

public class CastInsensitiveList extends ArrayList<String> {
    @Override
    public boolean contains(Object obj) {
        String object = (String)obj;
        for (String string : this) {
            if (object.equalsIgnoreCase(string)) {
              return true;
            }
        }
        return false;
    }
}

If you are using Java 8.0, using streaming API,

如果您使用的是 Java 8.0,使用流式 API,

List<String> arrayList = new ArrayList<>();
arrayList.stream().anyMatch(string::equalsIgnoreCase);

回答by ΦXoc? ? Пepeúpa ツ

The List#Ccontains()method check if the parameter is present in the list but no changes are made in the list elements

List#Ccontains()方法检查参数是否存在于列表中,但列表元素中未进行任何更改

use streams instead

改用流

public void leggTilOrd(String ordParameter) {
    final List<String> ord = Arrays.asList(new String[]{ "a", "A", "b" });
    final boolean ordExists = ord.stream().anyMatch(t -> t.equalsIgnoreCase(ordParameter));
    System.out.println(ordExists);
}

回答by Kaushik

If you want to avoid duplicates use HashSetinstead of List. Hashing works faster while searching. In the underlying class override the equals and hashcode method to return expected results using String.toUpperCase(). If you have a List of String, you can create a string wrapper class.

如果你想避免重复使用HashSet而不是 List。哈希在搜索时工作得更快。在底层类中覆盖 equals 和 hashcode 方法以使用String.toUpperCase(). 如果您有一个字符串列表,则可以创建一个字符串包装类。

String Wrapper could look like this:-

字符串包装器可能如下所示:-

public class CaseInsensitiveString {

    String string;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((string == null) ? 0 : string.toUpperCase().hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CaseInsensitiveString other = (CaseInsensitiveString) obj;
        if (string == null) {
            if (other.string != null)
                return false;
        } else if (!string.toUpperCase().equals(other.string.toUpperCase()))
            return false;
        return true;
    }

    // Other Methods to access string
}