I’ve a two POJOs, Sample code below
class A { String name; Object entries; // this can be a List<String> or a string - hence Object datatype //getters and setter here } class B { int snumber; List<A> values; //getters and setters here }
Controller class
class ControllerA { public getList(B b) { List<String> list = b.getValues().stream.map(e -> e.getEntries()).collect(Collectors.toList())); } }
This returns me a list of the list:
[[12345, 09876], [567890, 43215]]
but what I want is a single list like
[12345,09876,567890, 43215]
How can I do that with Java 8 streams?
I’ve tried flatMap
also, but that doesn’t go well with the Object
datatype of entries.
Advertisement
Answer
Consider a List<String>
as a field entries
in the A
class.
As @Eugene mentioned in the comments,
If it’s a single String make it a
List
of a single element; if it’s a list of multiple strings make it as such.
Working with a collection of a single type can simplify the process:
b.getValues() // -> List<A> .stream() // -> Stream<A> .map(A::getEntries) // -> Stream<List<String>> .flatMap(Collection::stream) // -> Stream<String> .collect(Collectors.toList()); // -> List<String>