-1

I'm in the process of learning streams. I have a conventional for loop which I would like to convert to stream.

Map<String, String> myMap = new HashMap<>();

for (Response response : responses) {

    if (!myMap.isEmpty()) {
        return myMap;
    }

 // some code related to response object
    
    if(some condition){
        myMap.put(key, value);
    }
//key and value is not property of response and coming from another object

}//end for

This is just pseudo code and there is more to it than shown. I'm struggling to return the map as shown above from the stream which is also my return type of method the code resides in. How do we achieve this?

heart_coder
  • 189
  • 13
  • 4
    why is the check `if (!myMap.isEmpty())` inside the loop? – f1sh Jul 03 '20 at 13:02
  • 1
    what collectors have you tried ? can you show your attemps at streaming ? – CharybdeBE Jul 03 '20 at 13:03
  • 1
    Seems like `return myMap;` should just be in the second if block (and the first one goes away) – ernest_k Jul 03 '20 at 13:04
  • @f1sh If the map is not empty, I would like to return and skip further iteration. – heart_coder Jul 03 '20 at 13:06
  • @heart_coder you can then just create an `Entry` instead of complete `Map`, why do you need a `Map`? Also, not sure what they `key` is, but you might have meant `myMap.put(key, response.value);` – Naman Jul 03 '20 at 13:08
  • @heart_coder the map can only be not empty if you `put` something into it. so add the return statement to the block where you perform the `put`. – f1sh Jul 03 '20 at 13:09
  • This is just a pseudo code. Whatever I have shown is just the sample model of actual implementation. Let's not worry about where that return should be. – heart_coder Jul 03 '20 at 13:09
  • Does this answer your question? [Java 8 List into Map](https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v) – Arvind Kumar Avinash Jul 03 '20 at 13:11
  • 1
    And what kind of answer do you expect when all you’ve give, is some “pseudo code” we should not worry about? – Holger Jul 03 '20 at 15:40

1 Answers1

1

I guess what you want is

Map<String, String> myMap = responses.stream()
    .filter(r -> r.value != null)
    .collect(toMap(r -> r.key, r -> r.value)); // I hope key and value are
                                               // properties of response,
                                               // it's not obvious from your code

(Which BTW is not what your code actually does. Your code stores only first response with nonnull value into map. Equivalent in streams would be .limit(1) after filter().)

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Tomáš Záluský
  • 10,735
  • 2
  • 36
  • 64