ArrayList contains case sensitivity

前端 未结 19 1830
故里飘歌
故里飘歌 2020-11-27 17:14

I am currently using the contains method belonging to the ArrayList class for making a search. Is there a way to make this search case insensitive in java? I found that in C

19条回答
  •  无人及你
    2020-11-27 18:03

    Traditionally, you can develop your own logic to compare strings held by an ArrayList. There may be several ways to do so like the one shown below.

    public boolean containsCaseInsensitive(String strToCompare, ArrayListlist)
    {
        for(String str:list)
        {
            if(str.equalsIgnoreCase(strToCompare))
            {
                return(true);
            }
        }
        return(false);
    }
    

    Why shouldn't be used some direct and convenient ways like a SortedSet as shown below with a case insensitive comparator?.

    Set a = new TreeSet(String.CASE_INSENSITIVE_ORDER);
    
    a.add("A");
    a.add("B");
    a.add("C");
    
    
    Set b = new TreeSet(String.CASE_INSENSITIVE_ORDER);
    
    b.add("a");
    b.add("b");
    b.add("c");
    
    System.out.println(b.equals(a));
    

    Would compare two different sets ignoring case and return true, in this particular situation and your comparision would work without any issue.

提交回复
热议问题