Rust中的zip算子很方便,能对两个集合进行平行处理,例如:
fn main() {
let vec1 = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let vec2 = vec![11, 22, 33, 44, 55, 66, 77, 88, 99];
let rest: Vec<i32> = vec1.iter().zip(vec2).map(|(e1, e2)| e1 + e2).collect();
println!("{:?}", rest);
}
// 输出结果:[12, 24, 36, 48, 60, 72, 84, 96, 108]
那么Java中可以进行类似的操作吗?
答案显然是标准库中没有直接提供类似的方案,可以操作,但会比较蛋疼。
但是!但是!google的guava库中以工具类的方式提供了这个算子,让我们欢呼吧🥰
package com.demos;
import com.google.common.collect.Maps;
import com.google.common.collect.Streams;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public final class Main {
public static void main(String[] args) {
Map<String, List<String>> map1 = LinkedHashMap.newLinkedHashMap(3);
Map<String, List<String>> map2 = LinkedHashMap.newLinkedHashMap(3);
map1.put("One", List.of("AAA", "BBB", "CCC"));
map1.put("Two", List.of("DDD", "EEE", "FFF"));
map1.put("Three", List.of("GGG", "HHH", "III"));
map2.put("first", List.of("J00", "K01", "L02"));
map2.put("second", List.of("M03", "N04", "O05"));
map2.put("third", List.of("P06", "Q07", "R08"));
Map<String, List<String>> result = Streams.zip(
map1.entrySet().stream(),
map2.entrySet().stream(),
(e1, e2) -> Maps.immutableEntry(
e1.getKey() + "-" + e2.getKey(),
Streams.zip(
e1.getValue().stream(),
e2.getValue().stream(),
(e01, e02) -> e01 + "-" + e02
).toList()
)
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(result);
}
}
// 输出结果:{One-first=[AAA-J00, BBB-K01, CCC-L02], Two-second=[DDD-M03, EEE-N04, FFF-O05], Three-third=[GGG-P06, HHH-Q07, III-R08]}
完美 撒花🎉🎉🎉🎉🎉🎉🎉🎉