Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Find Element in Array using Condition and Lambda

In short, I have this code, and I'd like to get an specific element of the array using a condition and lambda. The code would be something like this:

Preset[] presets = presetDALC.getList(); Preset preset = Arrays.stream(presets).select(x -> x.getName().equals("MyString")); 

But obviously this does not work. In C# would be something similar but in Java, how do I do this?

like image 748
Joe Almore Avatar asked Aug 28 '15 01:08

Joe Almore


People also ask

Can we use if condition in lambda expression Java?

The 'if-else' condition can be applied as a lambda expression in forEach() function in form of a Consumer action.

How do you check if an object is in an array Java?

The isArray() method of Class is used to check whether an object is an array or not. The method returns true if the given object is an array. Otherwise, it returns false .


2 Answers

You can do it like this,

Optional<Preset> optional = Arrays.stream(presets)                                    .filter(x -> "MyString".equals(x.getName()))                                    .findFirst();  if(optional.isPresent()) {//Check whether optional has element you are looking for     Preset p = optional.get();//get it from optional } 

You can read more about Optional here.

like image 132
akash Avatar answered Sep 21 '22 16:09

akash


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.

like image 29
Robby Cornelissen Avatar answered Sep 25 '22 16:09

Robby Cornelissen