简体   繁体   中英

How do I simultaneously iterate through a list and a set while pairing them in another map (using stream)

What i've tried is creating an iterator for the list and using stream on the set as such

Set //some object which has a getId method
Iterator<String> iterator = list.iterator();
someSet.stream()
     .map(Collectors.toMap(e -> e.getId(), e -> iterator.next() );

I think, what you wat to achieve is called "zip" in fuctional programming. This would be in Java to make a new stream from two existing streams by combining each of two corresponding elements of the given streams.

Look at this question to see how to do it:

Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

The Stream API is designed to work and iterate through one and only one collection and no more.

If you want to achieve such iteration called "zipping", as mentioned in the another answer, you have to iterate the indices. Since Set is not ordered, you have to use List instead and know the order is not predictable.

However, the usage of Stream API should be fine here:

Set<MyObject> set = ...                                             // MyObject with getId method
List<MyObject> listFromSet = new ArrayList<>(set);
List<MyObject> list = ...                                           // existing list

IntStream.range(0, Math.min(list.size(), listFromSet.size()))
        .mapToObj(index -> new AbstractMap.SimpleEntry<>(
            listFromSet.get(index).getId(),                         // key
            list.get(index))                                        // value
        )
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); // to Map

Few notes:

  • To know the highest number you can iterate through, you need ti find a lower from the sizes of the iterables: Math.min(list.size(), listFromSet.size()) .
  • map(Collector.toMap(...)) doesn't convert a Stream to Map but is not a valid construct, moreover the method map is not a terminal operation. Use .collect(Collectors.toMap(...)) instead which is.
  • Not all the keys from set might be used, not all the values from list might be used, there is no guaranteed order of the keys and the matching key-value will be random.
  • If I were to implement this, I'd definetly go for the simple for-loop iteration over the Streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM