Check if List / ArrayList contains Java string characters
I want to check if a string is found in the specified 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 list of letters, so I should see that my score is 3 because I found 3 matches for a string in my list. Anyway, the counter is printed with a value of 0. The basic idea is that I have to check if str is found in the list, regardless of the order of the letters in str.
You are comparing String
with Character
, so it equals
returns false
.
Compare char
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++;
}
}
}
Yours list
is supposed to contain only one String
s character . BTW, if this happens, you replace it with 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++;
}
}
}
The string is not equal to the character, so you need to convert the character to string.
if (list.get(i).equals(String.valueOf(str.charAt(j))))
or a string to char and compare it like this:
if (list.get(i).getCharAt(0)==str.charAt(j))
You can use streams
to get the answer in one line like 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 character to string:
list.get(i).equals(String.valueOf(str.charAt(j)))
The correct syntax for converting a character to a 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, that's right. Thanks for this. And I just checked now and saw that I could make my list:
ArrayList<Character> list ;
instead
ArrayList<String> list ;