在不区分大小写的情况下检查ArrayList是否包含某个String [英] Checking if an ArrayList contains a certain String while being case insensitive

查看:818
本文介绍了在不区分大小写的情况下检查ArrayList是否包含某个String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我要创建的方法:

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

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

推荐答案

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

You will need to iterate over the list and check each element. This is what is happening in the contains method. Since you are wanting to use the equalsIgnoreCase method instead of the equals method 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).

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

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

这篇关于在不区分大小写的情况下检查ArrayList是否包含某个String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆