transform List using lambda expressions [duplicate] - java

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())

Related

Combining orElseThrows? [duplicate]

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>>.

How do I go from Stream<ArrayList<Object>>> to ArrayList<Object> in Java? [duplicate]

This question already has answers here:
Java 8 Streams FlatMap method example
(7 answers)
Closed 3 years ago.
I have a Stream<ArrayList<Object>> and I want to "extract" the ArrayList from it and assign it to a variable. How do I do that?
My resulting variable needs to be of type ArrayList<Object> so I can iterate over it and do stuff.
If you want to get one ArrayList then use
ArrayList<Object> result = strm.flatMap(ArrayList::stream)
.collect(Collectors.toCollection(ArrayList::new));
Stream.flatMap method lets you replace each value of a stream with
another stream and then concatenates all the generated streams into a single stream.
List<Object> objectList = new ArrayList<>();
List<Object> collect = Stream.of(objectList)
.flatMap(m -> m.stream())
.collect(Collectors.toList());

Java streams statement: find the error [duplicate]

This question already has answers here:
Why does this java 8 stream operation evaluate to Object instead of List<Object> or just List?
(2 answers)
Why do we have to cast the List returned by Collectors.toList() to List<Integer> even though the elements of the Stream are already mapped to Integer? [duplicate]
(1 answer)
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 4 years ago.
This works as expected
Collection<String> items = combo.getItems();
items.stream().filter(item -> item.startsWith("New")).findFirst()...
But this fails to compile. Why?
Collection items = combo.getItems();
items.stream().map(Object::toString).filter(item -> item.startsWith("New")).findFirst()...
^^^^^^^^^^

JAVA8: Map list of objects to String[] [duplicate]

This question already has answers here:
How to convert a Java 8 Stream to an Array?
(9 answers)
Closed 5 years ago.
I have a List of 'Client' objects each one with a field "email".
I need something like:
List<String> listEmails = clients.stream().map(client->client.getEmail())
.collect(Collectors.toList());
...but returning directly a String[].
Is there a proper way to map a List<Client> to a String[] listEmails using Java 8 streams?
Sure :
String[] result = clients
.stream()
.map(client->client.getEmail())
.toArray(String[]::new)

Converting String of digits to List of integer [duplicate]

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());

Categories