There is a contains method for lists, so you should be able to do:
Arrays.asList(yourArray).contains(yourObject);
Warning: this might not do what you (or I) expect, see Tom's comment below.
Answer from Douglas on Stack OverflowThere is a contains method for lists, so you should be able to do:
Arrays.asList(yourArray).contains(yourObject);
Warning: this might not do what you (or I) expect, see Tom's comment below.
With Java 8, you can do this:
int[] haystack = {1, 2, 3};
int needle = 3;
boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);
You'd need to do
boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));
if you're working with objects.
A better way to find the index of an element in an array?
Java - Find Element in Array using Condition and Lambda - Stack Overflow
Java while loop to find index of elements in ArrayList
[java] How to access the last element in a two dimensional array of unknown size?
Currently the best way I have found is to typecast the array into an ArrayList, and using ArrayList's method .indexOf to get the index, for e.g:
import java.util.Arrays;
int[] arr = {2,3,4,5};
Arrays.asList(arr).indexOf(4); // returns 2Is this the best way? Or unnecessary wrapping?
You can do it like this,
Optional<Preset> optional = Arrays.stream(presets)
.filter(x -> "MyString".equals(x.getName()))
.findFirst();
// Check whether optional has element you are looking for
if (optional.isPresent()) {
Preset p = optional.get(); // Get it from optional
}
You can read more about Optional here.
Like this:
Optional<Preset> preset = Arrays
.stream(presets)
.filter(x -> x.getName().equals("MyString"))
.findFirst();
This will return an Optional which might or might not contain a value. If you want to get rid of the Optional altogether:
Preset preset = Arrays
.stream(presets)
.filter(x -> x.getName().equals("MyString"))
.findFirst()
.orElse(null);
The filter() operation is an intermediate operation which returns a lazy stream, so there's no need to worry about the entire array being filtered even after a match is encountered.