简体   繁体   中英

How to Copy elements of list type A & B to new list type C using stream

I have a list-A and List-B considering both are of same length, Now i would like to generate a List-C by copying each of A and B to C, where C is a class consisting of fields A and B, can any suggest how could i achieve this using stream.

Code without using stream:

int i=0;
List<key> keys = cmdBody.getKeys();
List<value> values = storage.getValues();
List <KeyValue> keyValues = new ArrayList<>();
keys.forEach(key -> {
    KeyValue keyValue = new KeyValue();
    keyValue.setKey(key);
    keyValue.setValue(values.get(i++));
    keyValues.add(keyValue);
});

You can use IntStream and it will be easier if you have a arguments constructor in KeyValue class

IntStream.range(0, keys.size())
             .mapToObj(i -> new KeyValue(keys.get(i), values.get(i)))
             .collect(Collectors.toList());

Here's one way:

First, create streams of the two lists. Then, zip the two streams. For how to zip two streams, see here .

Now you can do:

zip(keys.stream(), values.stream(), (k, v) -> {
    KeyValue keyValue = new KeyValue();
    keyValue.setKey(k);
    keyValue.setValue(v);
    return keyValue;
}).collect(Collectors.toList());

It would be really helpful if KeyValue had an AllArgsConstructor that looked something like this:

public KeyValue(key k, value v) {
    setKey(k);
    setValue(v);
}

because then you could just do:

zip(keys.stream(), values.stream(), KeyValue::new)
    .collect(Collectors.toList());

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