This question already has answers here:
Use Java 8 Optional in existing Java 7 code
(4 answers)
Flattening a list of elements in Java 8 Optional pipeline
(2 answers)
Java 8 Optional and flatMap - what is wrong?
(1 answer)
What is the difference between Optional.flatMap and Optional.map?
(8 answers)
Closed 2 years ago.
I have the following code and it works as expected:
Optional.ofNullable(testItem.getId())
.map(testItemRepository::get)
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID))
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID));
I would like to know if there is a way to just have one orElseThrow-Part or do it less redundant ?
Use Optional#flatMap method that flattens the Optional structure as long the call of the method testItemRepositoryget results in Optional.
Optional.ofNullable(testItem.getId())
.flatMap(testItemRepository::get)
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID));
I.e. from Optional<Optional<MyObject>> to Optional<MyObect>.
It seems to be the case that testItemRepository::get returns another Optional<Something>. In that case, you should not use map. Using map will get you a nested optional - Optional<Optional<Something>>, which as you have found out, is not nice to work with. flatMap is made for exactly this situation:
Optional.ofNullable(testItem.getId())
.flatMap(testItemRepository::get)
.orElseThrow(() -> new TestException(ReturnCode.UNKNOWN_ID));
flatMap turns an Optional<A> to an Optional<B>, given a Function<A, Optional<B>>.
Related
This question already has answers here:
How can I turn a List of Lists into a List in Java 8?
(12 answers)
Closed 2 years ago.
I have created a function to transform the elements of a list:
private List<Hostel> build(List<Hotel> hotels) {
return hotels.stream().map(h -> convert(h)).collect(toList());
}
but I have a compilation error:
required type: List<Hostel>
Provided: List<List<Hostel>>
From your error it seems convert(h) return a List<Hostel>, for that when you use a map, and collect the result is List<List<Hostel>>, to get List<Hostel>, you have to use flatMap instead of map, like this:
.flatMap(h -> convert(h).stream())
This question already has answers here:
How to check if a Java 8 Stream is empty?
(8 answers)
Closed 3 years ago.
I am curious if it's possible to use orElseThrow() in the following situation or if there a more Java 8 way to do the equivalent of this as a 1-liner?
Collection<Foo> foo = blah.stream().filter(somePredicate).collect(Collectors.toList());
if (foo.isEmpty()) {
throw new Exception("blah");
}
You could try this:
Collection<Foo> foo = blah.stream().filter(somePredicate)
.collect(Collectors.collectingAndThen(Collectors.toList(), Optional::of))
.filter(l -> !l.isEmpty())
.orElseThrow(() -> new Exception("blah"))
Note that comparing to your code this allocates an extra Optional instance.
This question already has an answer here:
Chaining of Java Optional map and orElse (if-else-style)
(1 answer)
Closed 4 years ago.
I found myself writing this:
Optional<String> s = fooMaybe.map(Foo::getName).orElse(Optional.empty());
Of course, for the return types to match the compilable way is:
Optional<String> s = fooMaybe.map(foo -> Optional.of(foo.getName)).orElse(Optional.empty());
But is there not a more succinct way? e.g. Does Optional.of(null) return Optional.empty()?
Optional<String> s = Optional.of(fooMaybe.map(Foo::getName).orElse(null));
D'oh. I wasn't realizing that map also returns an Optional of the type being mapped. So all along it was...
Optional<String> s = fooMaybe.map(Foo::getName);
I'll keep this question open for other newbies tripping over their own feet.
This question already has answers here:
Collection to stream to a new collection
(4 answers)
Closed 7 years ago.
So, in Clojure, I can just say something like this...
(into [] (map some-function some-collection))
And I get a new vector of my transformed data.
Is there some simple equivalent of into for Java 8 streams? For example, I don't see a constructor on ArrayList that takes a stream, nor do I see some sort of helper function in java.util.Collections, nor the stream interface.
You can do it using Collectors:
someCollection.stream()
.map(someFunction)
.collect(Collectors.toList());
You can do other cool stuff with Collectors, as explained in its javadoc:
Map<Department, Integer> totalByDept =
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));
This question already has answers here:
How do I convert a Java 8 IntStream to a List?
(5 answers)
Closed 7 years ago.
I am doing some hands on exercise on java 8 stream features so thought of applying the knowledge with the problem Converting String of digits to List of integer
a typical test would look like
#Test
public void testGetListofIntegersFromString(){
List<Integer> result = getIntegers("123456780");
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,0),result);
}
I have written below method
List<Integer> getIntegers(String value) {
return IntStream.rangeClosed(0, value.length() - 1).map(i -> Integer.valueOf(value.substring(i,i+1))).collect(?????);
}
I am stuck about which function to use to get The List Of Integers
I tried collect(Collectors.toList()) Its giving compilation error.
Please suggest if we can follow different to solve this .
Use String.chars():
"123456780".chars().map(c -> c-'0').boxed().collect(Collectors.toList());