2

I have a set of keys.

class X { private static String[] keys = {"k1", "k2", ... }; 

I have to extract values for the keys from a request. I think I can use map to extract values and create a list necessary objects in some request processing method like this:

 public void processReq(Request req) { ... Stream.of(keys).map(k-> new Pack(k, req.getHeader(k))); 

But creating Stream per every request looks unnecessary task. If sharing Stream instance among multiple threads is safe, I think I can modify the code like this:

class X { private static Stream<String> keys = Stream.of("k1", "k2", ...); ... public void processReq(Request req) { ... keys..map(k-> new Pack(k, req.getHeader(k))); 

So, is sharing Stream instance among multiple threads like this safe?

2
  • 5
    This won't even work. A Stream can only be traversed once. Commented Apr 6, 2016 at 16:27
  • 4
    And creating a Stream over an array doesn't take any time. What takes time is to traverse it. Commented Apr 6, 2016 at 16:29

2 Answers 2

6

Streams are not intended to be used more than once, even in the same thread. If you want to have a collection, use a List (or an array)

 private static final List<String> keys = Arrays.asList("k1", "k2", ...); 

This can be used multiple times.

List<Pack> packs = keys.stream() .map(k-> new Pack(k, req.getHeader(k))) .collect(Collectors.toList()); 

In your code, the new Pack or req.getHeader is where most of the time is spent.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.