3 回答
TA贡献1886条经验 获得超2个赞
使用IntStream
并收集到地图:
IntStream.range(0, a.length) .boxed() .collect(toMap(i -> a[i], i -> b[i]));
TA贡献1809条经验 获得超8个赞
为了完整起见,如果你不喜欢拳击IntStream(感觉没有必要),你可以这样做,例如:
Double[] a = new Double[]{1.,2.,3.};
Double[] b = new Double[]{10.,20.,30.};
Map<Double, Double> myMap = IntStream.range(0, a.length)
.collect(HashMap::new, (m, i) -> m.put(a[i], b[i]), Map::putAll);
System.out.println(myMap);
该片段的输出是:
{1.0=10.0, 2.0=20.0, 3.0=30.0}
TA贡献2011条经验 获得超2个赞
我们可以使用提供索引的Collectors.toMap()from来做到这一点:IntStream
Double[] a = new Double[]{1.,2.,3.};
Double[] b = new Double[]{10.,20.,30.};
Map<Double, Double> map =
IntStream.range(0, a.length)
//If you array has null values this will remove them
.filter(idx -> a[idx] != null && b[idx] != null)
.mapToObj(idx -> idx)
.collect(Collectors.toMap(idx -> a[idx], idx -> b[idx]));
我们还可以将 映射IntStream到对象流Map.Entry<Double, Double>,然后使用Collectors.toMap():
Double[] a = new Double[]{1.,2.,3.};
Double[] b = new Double[]{10.,20.,30.};
Map<Double, Double> map =
IntStream.range(0, a.length)
.filter(idx -> a[idx] != null && b[idx] != null)
.mapToObj(idx -> new AbstractMap.SimpleEntry<Double, Double>(a[idx], b[idx]))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
添加回答
举报