Java array contains any of

Java array contains any element of another list

Solution: Basically Room Database Stores data in primary data types. Solution 1: You can use a combination of and : Solution 2: Intersect Solution 3: Using from the standard Java utilities can determine if two collections contain any common members.

ArrayList contains one or more entities from another ArrayList [duplicate]

Like list2.stream().anyMatch(list1::contains) in java 8.

Pre-Java 8, you can use retainAll to achieve this quite simply:

Set intersect = new HashSet<>(listOne); intersect.retainAll(listTwo); return !intersect.isEmpty(); 

There’s no need to use streams for this task. Use the Collections.disjoint method instead:

boolean result = !Collections.disjoint(list1, list2); 

Returns true if the two specified collections have no elements in common.

Something like ‘contains any’ for Java set?, I have two sets, A and B, of the same type. I have to find if A contains any element from the set B. What would be the best way to do that

Something like ‘contains any’ for Java set?

Wouldn’t Collections.disjoint(A, B) work? From the documentation:

Returns true if the two specified collections have no elements in common.

Thus, the method returns false if the collections contains any common elements.

Stream::anyMatch

Since Java 8 you could use Stream::anyMatch .

setA.stream().anyMatch(setB::contains) 

Apache Commons has a method CollectionUtils.containsAny() .

Check if list contains at least one of another, Collections.disjoint returns true if the two specified collections have no elements in common. If it returns false , then your list has at

How to find if a list contains any element of another list in sqlite

Basically Room Database Stores data in primary data types. So your selected dates are in TEXT format. You can perform LIKE operation to find the matching columns.

Room also provides a annotation @RawQuery . You can use this. For your problem this might be a solution:

@RawQuery(observedEntities = Schedule.class) LiveData> getSchedule(SupportSQLiteQuery query); 
String query = "SELECT * FROM schedule_table WHERE " + "(type_daily IS 1) OR (" + monthOfYear + " IS 1) OR " + conditions + " ORDER BY scheduleID DESC"; return mDao.getSchedule(new SimpleSQLiteQuery(query)); 

where condition is the String of the dates you want to find. For example:

String condition = "selectedDates LIKE '%%' OR selectedDates LIKE '%%'; 

You can create a method which will generate this string based on a List .

How can I check if an ArrayList contains any elements from, You can use. Collections.disjoint(singingGroup, Arrays.asList(Winners));. to test, is the 2 arguments have no common element(s) in common.

How to check if collection contains any element from other collection in Scala?

You can use a combination of exists(p: T => Boolean):Boolean and contains(elem: A1):Boolean :

val a = List(1,2,3,4,5,6,7) val b = List(11,22,33,44,55,6) a.exists(b.contains) // true 
val a = Seq(1,2,3) ; val b = Seq(2,4,5) a.intersect(b) res0: Seq[Int] = List(2) // to include the test: a.intersect(b).nonEmpty // credit @Lukasz 

Using disjoint() from the standard Java Collections utilities can determine if two collections contain any common members. If the collections are not disjoint, then they contain at least one common element.

Internally, Collections.disjoint() checks if either collection is a Set and optimizes accordingly.

import collection.JavaConverters._ val a = List(1,2,3,4,5,6,7) val b = List(11,22,33,44,55,6) !java.util.Collections.disjoint(a.asJava, b.asJava) // true 

Although this is still converting the Scala collection to a Java collection. On the plus side, the extra apache commons library isn’t needed.

Читайте также:  Блок с тенью

ArrayList contains one or more entities from another, Like list2.stream().anyMatch(list1::contains) in java 8.

Источник

How to Check if Java Array Contains a Value?

How to Check if Java Array Contains a Value?

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

How to Check if Java Array Contains a Value?

  • Simple iteration using for loop
  • List contains() method
  • Stream anyMatch() method
  • Arrays binarySearch() for sorted array

Let’s look into all these methods one at a time.

1. Using For Loop

This is the easiest and convenient method to check if the array contains a certain value or not. We will go over the array elements using the for loop and use the equals() method to check if the array element is equal to the given value.

String[] vowels = < "A", "I", "E", "O", "U" >; // using simple iteration over the array elements for (String s : vowels) < if ("E".equals(s)) < System.out.println("E found in the vowels list."); >> 

2. Using List contains() method

We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value. Let’s use JShell to run the example code snippet.

jshell> String[] vowels = < "A", "I", "E", "O", "U" >; vowels ==> String[5] < "A", "I", "E", "O", "U" >jshell> List vowelsList = Arrays.asList(vowels); vowelsList ==> [A, I, E, O, U] jshell> vowelsList.contains("U") $3 ==> true jshell> vowelsList.contains("X") $4 ==> false 

Java Array Contains Value

3. Using Stream anyMatch() Method

If you are using Java 8 or higher, you can create a stream from the array. Then use the anyMatch() method with a lambda expression to check if it contains a given value.

jshell> List vowelsList = Arrays.asList(vowels); vowelsList ==> [A, I, E, O, U] jshell> Arrays.stream(vowels).anyMatch("O"::equals); $5 ==> true jshell> Arrays.stream(vowels).anyMatch("X"::equals); $6 ==> false 

4. Arrays binarySearch() for sorted array

If your array is sorted, you can use the Arrays binarySearch() method to check if the array contains the given value or not.

String[] vowels = < "A", "I", "E", "O", "U" >; System.out.println("Unsorted Array = " + Arrays.toString(vowels)); Arrays.parallelSort(vowels); System.out.println("Sorted Array = " + Arrays.toString(vowels)); int index = Arrays.binarySearch(vowels, "X"); if (index < 0) < System.out.println("X not found in the array"); >else
Unsorted Array = [A, I, E, O, U] Sorted Array = [A, E, I, O, U] X not found in the array 

Checking if Array Contains Multiple Values

What if we want to check if the array contains multiple values. Let’s say you want to check if a given array is the subset of the source array. We can create nested loops and check each element one by one. There is a cleaner way by converting arrays to list and then use the containsAll() method.

String[] vowels = < "A", "I", "E", "O", "U" >; String[] subset = < "E", "U" >; boolean foundAll = Arrays.asList(vowels).containsAll(Arrays.asList(subset)); System.out.println("vowels contains all the elements in subset = " + foundAll); 

Output: vowels contains all the elements in subset = true

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

How to check if array contains a value in java

Check if array contains value in java
This article will detail out 5 different methods to check if array contains a value in java with example programs.
Following are the methods to check the presence of a value in java array

Читайте также:  Create csv table python

We will be performing the following tasks :

  1. Check whether a string array contains a given string value.
  2. If the string exists in the array, then get the index of its position in array.

Method 1 : Looping over the array
This is a conventional and most used method where the array of strings is iterated using a for loop and the value at every index is compared with the value to be searched in the array.
A boolean variable is set if any array value matches with the string. At the end of the loop, this boolean variable is checked to determine if the array contains the string.

public class ArrayContainsChecker < public static void main(String[] args) < methodOne(); >static void methodOne() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "three"; // initialize boolean variable boolean isExists = false; // iterate over array for (int i = 0; i < array.length; i++) < // get the value at current array index String arrayValue = array[i]; // compare values if (valueToSearch.equals(arrayValue)) < isExists = true; // if value is found, terminate the loop break; >> if (isExists) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Use == operator to check for equality when comparing primitive types such as int, long, float, double etc.
Note that in this example, we are using a simple for loop with an index.
But, we may also use an enhanced for loop to iterate over the array , if we do not require the index of the value to check.

Method 2 : Using List.contains()
Another method to check if an array contains an element is by using a list.
This method first converts the array to a java.util.List and then uses contains() method of java.util.List to check if the string exists in the list.

contains() method returns true if the value supplied as argument exists in the list and false otherwise. In other words, it checks if the list contains the supplied value.
Array is converted to a list using asList method of java.util.Arrays . This method takes an array as argument and returns a List with its elements populated with the contents of array.

import java.util.Arrays; import java.util.List; public class StringChecker < public static void main(String[] args) < methodTwo(); >static void methodTwo() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "three"; // convert the array to a list List list = Arrays.asList(array); // check if string exists in list if (list.contains(valueToSearch)) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Method 3 : Using Apache Commons Library
This method utilizes ArrayUtils class from Apache Commons Library.
This class has a method contains() which takes two arguments : an array and a value. It searches for the value in the array and returns true if the value is found in the array, false otherwise.

import org.apache.commons.lang.ArrayUtils; public class StringChecker < public static void main(String[] args) < methodThree(); >static void methodThree() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "three"; // check if string exists in array if (ArrayUtils.contains(array, valueToSearch)) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Читайте также:  Using this in php class

Apache Commons can be included using the following dependencies of Maven and Gradle. Use as per to the build tool suitable to you.

 org.apache.commons commons-lang3 3.9 
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

Method 4 : Using Arrays.binarySearch()
java.util.Arrays has a binarySearch() method which searches for a value in an array using binary search algorithm.
This method takes two arguments :
1. an array, and
2. the item to search in the array
and returns the index of the item in the array.
It returns -1 if the element is not found in the array. Note that this method requires the array to be sorted before performing the search operation.

import java.util.Arrays; public class StringChecker < public static void main(String[] args) < methodFour(); >static void methodFour() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "one"; // sort the array Arrays.sort(array); // search the value and get its index int index = Arrays.binarySearch(array, valueToSearch); // if index is not -1 then value is present if (index != -1) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Method 5 : Java 8 anyMatch()
With java 8 stream you can directly get an element matching some value. For using streams, the array should be converted to a collection class.
Convert it to a java.util.List using asList() method of java.util.Arrays class.
On this list object call stream() method which returns a java.util.stream.Stream object.

Invoke anyMatch() method on this stream object. This method takes a java.util.function.Predicate object as argument.

A Predicate object can be created on the fly using java Lambda expression by writing an expression which returns a boolean value.

In the below example, the expression is s -> s.equals(valueToSearch) . Here s represents the elements of array and compares them with the value we want to search in the array.
Thus the line list.stream().anyMatch(s -> s.equals(valueToSearch)) compares the elements of the list with the value to search and returns true if any element of the list matches the string in variable valueToSearch .

import java.util.Arrays; import java.util.List; public class StringChecker < public static void main(String[] args) < methodFive(); >static void methodFive() < // initialize array String[] array = < "one", "two", "three", "four" >; // initialize value to search String valueToSearch = "one"; // convert the array to a list List list = Arrays.asList(array); // check if array contains value boolean isFound = list.stream().anyMatch(s -> s.equals(valueToSearch)); if (isFound) < System.out.println("String is found in the array"); >else < System.out.println("String is not found in the array"); >> >

String is found in the array

Let’s tweak in

  1. binarySearch() method will return -1 even if the value is present in the array if the array is not sorted.
  2. binarySearch() method can also be used directly in situations when the index of the value in the array is required.
  3. Arrays.asList will throw a java.lang.NullPointerException if the array supplied as argument is null .
  4. ArrayUtils from Apache Commons library also iterates over the array and compares each element with the value to search.
  5. There are different overloaded versions of contains method in ArrayUtils from Apache Commons library which act on arrays of various data types such as char , float , double , int , long , short etc.
  6. All the above methods work on string arrays but they can be used to search an element in array of other data types such as int array, char array etc.

Hope the article was useful.

Источник

Оцените статью