Reputation: 7429
Given is a list of Strings that needs to be filtered. I know that the result is always one String. I want to get this value. Is there a better solution than doing this
List<String> bla = new ArrayList();
bla
.stream()
.filter(s->s.equals("something"))
.collect(Collectors.toList())
.get(0);
Something like getOrDefault would be awesome.
Upvotes: 2
Views: 11460
Reputation: 22402
You can use findFirst
which returns Optional
object and then use Optional.orElseGet
to set your default value.
Optional<String> optString = bla.stream()
.filter(s->s.equals("something")).findFirst();
String somethingValue = optString.orElseGet(() -> "DEFAULT_VALUE");
Also, I strongly suggest, not to directly invoke the get()
method as it will throw NoSuchElementException
, look here for details, but you can use orElseGet
as shown above.
Upvotes: 3
Reputation: 31841
You can use .findFirst()
.
But since you're sure that there will be only 1 element in the list that you're searching for, then you can use .findFirst()
or .findAny()
which returns an Optional.
You can then get your object by simply calling get()
of this Optional
class.
List<String> bla = new ArrayList();
String bla2 = bla
.stream()
.filter(s -> s.equals("something"))
.findAny()
.get();
System.out.println(bla2);
Example
import java.util.stream.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
List < String > bla = new ArrayList();
bla.add("one");
bla.add("something");
bla.add("two");
String bla2 = bla
.stream()
.filter(s -> s.equals("something"))
.findAny()
.get();
System.out.println(bla2);
}
}
Output
something
Upvotes: 2
Reputation: 87
Rather than using
bla.stream()
.filter(s->s.equals("something"))
.collect(Collectors.toList())
.get(0);
You can use the following
bla
.stream()
.filter(s->s.equals("something"))
.collect(Collectors.toList());
get(0)
is not required
Upvotes: -2