Very new to stream API's so pardon me if this is a basic question. I am trying to convert this code snippet to use Java 8 stream
Resultset results = new Resultset();
List<Object[]> terms = service.search(term);
Map<Long, TermResult> resultMap = new HashMap<Long, TermResult>();
for(Object[] term : terms) {
Long id = (Long)term[0];
String termStr = (String)term[1];
TermResult termResult = new TermResult(id, termStr);
resultMap.put(id, termResult);
results.addResult(termResult);
}
terms
is a list of object array with id in Object[0]
and term in Object[1]
.The above code basically does the following -
- Convert the
terms
list toresultMap
with the keyid
and valueTermResult
object - Add the
TermResult
into aresults
set
I was able to convert #1 to use stream -
Map<Long, TermResult> resultMap =
terms.stream().collect(Collectors.toMap(p -> (Long)p[0], p -> new TermResult((Long)p[0], (String)p[1])));
But how would I sneak in #2 in the above pipeline?
This is what I came up with using peek
-
Map<Long, TermResult> resultMap =
terms.stream().map(p -> new TermResult((Long)p[0], (String)p[1]))
.peek(p -> results.addResult(p))
.collect(Collectors.toMap(p -> p.getId(), p -> p));
- Is this the right way to do this?
- Also can this be done in parallel? I want
results
to be in same order asterms
list(sorted by term). I tried usingparallelStream
in the above code snippet. But the order is not preserved inresults
.
Thank you for your inputs!