There are a few ways.
Which one you choose is up to you, there's a tradeoff between verbosity, being constrained to a simple equals check (if you want to do more complicated matching, you can't easily do Option 1), and using newer APIs that you might not yet support or be familiar with.
Option 1: The Collection.contains() method:
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
if (fruits.contains("banana") {
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
Option 2: Using a for loop with external state:
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
boolean found = false;
for (String s : fruits) {
if (s.equals("banana")) {
found = true;
break; // Break out of the loop to skip the remaining items
}
}
if (found) {
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
Option 3: If you're using Java 8, the neat Stream.anyMatch() method:
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
if (fruits.stream().anyMatch(s -> s.equals("banana"))) {
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
Option 3 is my personal favorite, as it's nearly as compact as Option 1, but allows to to provide a more complex Predicate if you want a comparison based on something other than the equals() method.
There are a few ways.
Which one you choose is up to you, there's a tradeoff between verbosity, being constrained to a simple equals check (if you want to do more complicated matching, you can't easily do Option 1), and using newer APIs that you might not yet support or be familiar with.
Option 1: The Collection.contains() method:
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
if (fruits.contains("banana") {
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
Option 2: Using a for loop with external state:
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
boolean found = false;
for (String s : fruits) {
if (s.equals("banana")) {
found = true;
break; // Break out of the loop to skip the remaining items
}
}
if (found) {
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
Option 3: If you're using Java 8, the neat Stream.anyMatch() method:
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");
if (fruits.stream().anyMatch(s -> s.equals("banana"))) {
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
Option 3 is my personal favorite, as it's nearly as compact as Option 1, but allows to to provide a more complex Predicate if you want a comparison based on something other than the equals() method.
You don't have to iterate through the array list. Once you call list.contains("someString"), it will check for that string in that entire array list. Therefore, the following is enough.
if(fruit.contains("banana"){
System.out.println("Found");
} else {
throw new SkipException("could not be found");
}
How do I know if an array list contains an specific string
arrays - Java, return if trimmed String in List contains String - Stack Overflow
java - Check if a String is in an ArrayList of Strings - Stack Overflow
java - Test if a string contains any of the strings from an array - Stack Overflow
I created an array list out from a constructor, now what I want to do is that the program will only print those set of array list with the item that matches the search key. I tried using arraylist.contains but it won't work. Is there any method I can use to know whether the array contains a specific certain string? Thank you!
With Java 8 Stream API:
List<String> myList = Arrays.asList(" A", "B ", " C ");
return myList.stream().anyMatch(str -> str.trim().equals("B"));
You need to iterate your list and call String#trim for searching:
String search = "A";
for(String str: myList) {
if(str.trim().contains(search))
return true;
}
return false;
OR if you want to perform ignore case search, then use:
search = search.toLowerCase(); // outside loop
// inside the loop
if(str.trim().toLowerCase().contains(search))
EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.
public static boolean stringContainsItemFromList(String inputStr, String[] items) {
return Arrays.stream(items).anyMatch(inputStr::contains);
}
Also, if we change the input type to a List instead of an array we can use items.stream().anyMatch(inputStr::contains).
You can also use .filter(inputStr::contains).findAny() if you wish to return the matching string.
Important: the above code can be done using parallelStream() but most of the time this will actually hinder performance. See this question for more details on parallel streaming.
Original slightly dated answer:
Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings. A primitive way to make it case insensitive would be to call toLowerCase() or toUpperCase() on both the input and test strings.
If you need to do anything more complicated than this, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions. Once you understand those, you can use those classes or the String.matches() helper method.
public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
return true;
}
}
return false;
}
import org.apache.commons.lang.StringUtils;
String Utils
Use:
StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})
It will return the index of the string found or -1 if none is found.
you don't have to do this:
if(Arrays.asList(list).contains("Paul"))
because the identifier list is already an ArrayList
you'll need to do:
if(list.contains("Paul")){
System.out.println("Yes it does");
}
The reason why you not getting what you expected is the usage of
Arrays.asList(list)
which returns a new array with a single element of type array. If your list contains two elements [Paul, James], then the Arrays.asList(list) will be [[Paul, James]].
The correct solution for the problem already provided by 'Ousmane Mahy Diaw'
The following will also work for you:
// if you want to create a list in one line
if (Arrays.asList("Paul", "James").contains("Paul")) {
System.out.println("Yes it does");
}
// or if you want to use a copy of you list
if (new ArrayList<>(list).contains("Paul")) {
System.out.println("Yes it does");
}
Your code is more complicated than it needs to be, but it gets the job done.
The awkward part of your code is the use of the various index values i, j, and k. Really, you don't need them at all. If you rename things a bit, and use "enhanced-for" loops, it becomes:
public boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {
for(String title : titleOfVehicles) {
boolean found = false;
for(String model : models) {
if(title.contains(model)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
Note that the logic is essentially the same, but you focus on the important things. The found variable is a better name, and it's scope is limited to inside the outer for-loop. The hard-to-understand k loop-terminator is removed.
Note, using streams, and a regular expression, would actually be more compact solution, but may not be as readable... I played with the stream version and a regex, and got:
public static boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {
String pattern = models.stream()
.map(Pattern::quote)
.collect(Collectors.joining("|", ".*(", ").*"));
Pattern re = Pattern.compile(pattern);
return titleOfVehicles.stream()
.allMatch(t -> re.matcher(t).matches());
}
(which you can see working here: https://ideone.com/8sqKu7 )
The current code works but it is very awkward, as rolfl pointed out. I would add that you should never compare booleans with true or false, like what you're doing in:
} else if(k == models.size() - 1 && flag == false) {
return false;
}
Instead, have
} else if (k == models.size() - 1 && !flag) {
return false;
}
You can actually accomplish this task in a single, clear and easy line using the Stream API:
public boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {
return titleOfVehicles.stream().allMatch(t -> models.stream().anyMatch(t::contains));
}
This does exactly what is written: it returns whether all elements in the given titles contains any of the given models.
Both allMatch and anyMatch are short-circuiting operations, so it will behave exactly like your current code.