3 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
使用IntStream
并收集到地圖:
IntStream.range(0, a.length) .boxed() .collect(toMap(i -> a[i], i -> b[i]));

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
為了完整起見,如果你不喜歡拳擊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貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
我們可以使用提供索引的Collectors.toMap()from來做到這一點(diǎn):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到對(duì)象流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));
添加回答
舉報(bào)