1

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 -

  1. Convert the terms list to resultMap with the key id and value TermResult object
  2. Add the TermResult into a results 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));
  1. Is this the right way to do this?
  2. Also can this be done in parallel? I want results to be in same order as terms list(sorted by term). I tried using parallelStream in the above code snippet. But the order is not preserved in results.

Thank you for your inputs!

Code Geass
  • 291
  • 1
  • 2
  • 13
  • 2
    See also [β€œIn Java streams is peek really only for debugging?”](http://stackoverflow.com/q/33635717/2711488) – Holger May 25 '16 at 13:41

1 Answers1

3

No, it can't be done in parallel; certainly not if results is not thread-safe and even then not while preserving order. (And additionally -- adding parallelism before you've actually measured how long an operation takes is almost always a bad idea. Parallelism is more likely to hurt performance than help if you just slap it everywhere.)

All this said, streams are really not intended to do more than one thing at once. You'd almost certainly be better off just creating the map and then iterating through its values(), or just creating a Set out of them depending on what results actually is. You could do it the way you described, but you shouldn't.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413