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:
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.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.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.