简体   繁体   中英

Check if a List/ArrayList contains chars of a string Java

I want to check if a string is found in a given list filled with letters. For example , if i have :

ArrayList<String> list = new ArrayList();
list.add("a");
list.add("e");
list.add("i");
list.add("o");
list.add("u");

String str = "aeo";

for (int i = 0; i < list.size(); i++)
    for (int j = 0; j < str.length(); j++) {
        if (list.get(i).equals(str.charAt(j)))
            count++;
    }
System.out.println(count);

str is found in my letter list so I have to see my count having value 3 , because i've found 3 matches with the string in my list. Anyway, count is printed with value 0 . The main idea is that i have to check if str is found in the list no matter the order of the letters in str.

You are comparing a String to a Character , so equals returns false .

Compare char s instead :

for (int i = 0; i < list.size(); i++) {
    for (int j=0; j < str.length(); j++) {
        if (list.get(i).charAt(0) == str.charAt(j)) {
            count++;
        }
    }
}

This is assuming your list contains only single character String s. BTW, if that's the case, you would replace it with a char[] :

char[] list = {'a','e','i','o','u'};
for (int i = 0; i < list.length; i++) {
    for (int j = 0; j < str.length(); j++) {
        if (list[i] == str.charAt(j)) {
            count++;
        }
    }
}

A string is not equals a character, so you have to convert the character to a string.

if (list.get(i).equals(String.valueOf(str.charAt(j))))

or the string to a char and compare it like that:

if (list.get(i).getCharAt(0)==str.charAt(j))

You can use streams to get the answer in one line as shown below with inline comments:

ArrayList<String> list = new ArrayList();
//add elements to list

String str = "aeo";//input string

//split str input string with delimiter "" & convert to stream
long count = Arrays.stream(str.split("")).//splt the string to array
    filter(s -> list.contains(s)).//filter out which one matches from list
    count();//count how many matches found
System.out.println(count);

Convert the character to the string:

list.get(i).equals(String.valueOf(str.charAt(j)))

The correct syntax to convert character to the string is:

list.get(i).charAt(0) == str.charAt(j)

list.get(i).getCharAt(0)==str.charAt(j) won't work as written in Jens' answer.

Yes, this is right. Thanks for it . And I've also just checked now and saw that I could make my list :

ArrayList<Character> list ;

instead of

ArrayList<String> list ;

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