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.
source to share
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++;
}
}
}
source to share
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);
source to share