[英]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.我有一个 list-A 和 List-B 考虑到两者的长度相同,现在我想通过将 A 和 B 复制到 C 来生成一个 List-C,其中 C 是一个 ZA2F2ED4F8EBC2CBB4C21A29DC,任何建议我如何使用 stream 来实现这一点。
Code without using stream:不使用 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);
});
Here's one way:这是一种方法:
First, create streams of the two lists.首先,创建两个列表的流。 Then, zip the two streams.
然后, zip这两个流。 For how to zip two streams, see here .
有关如何 zip 两个流,请参见此处。
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:如果
KeyValue
有一个看起来像这样的AllArgsConstructor
,那将非常有帮助:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.