Search code examples
javahashmapjava-streamguava

Whats the best way to force Streams.zip to iterate over each element (using Guava, Java)


I am trying to use Streams.zip to create a map. I don't care about the stream returned result, I just need the lambda to execute for each element. Here is my code

String x[] = {"a", "b"};
String y[] = {"c", "d"};

var data = new HashMap<String, String>();

var myStream = Streams.zip(Arrays.stream(x), Arrays.stream(y),
                (arg1, arg2) -> { data.put(arg1, arg2); return 0; };
var result = myStream.collect(Collectors.toList()); // ideally don't want this line

Without the collect( ) line I don't populate the map, so what's simplest way to do this, I tried count() instead of collect but this shortcuts the zip entirely. Or is there a simpler one line solution without Streams.zip to populate a map from two lists?


Solution

  • You should use Streams#forEachPair instead:

    String x[] = {"a", "b"};
    String y[] = {"c", "d"};
    
    var data = new HashMap<String, String>();
    
    Streams.forEachPair(Arrays.stream(x), Arrays.stream(y), data::put);
    
    System.out.println(data); // {a=c, b=d}
    

    Obviously if you don't need to control HashMap, you can just collect:

    String x[] = {"a", "b"};
    String y[] = {"c", "d"};
    
    var result = Streams.zip(Arrays.stream(x), Arrays.stream(y), Maps::immutableEntry)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    
    System.out.println(result); // {a=c, b=d}