3 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個贊
在任何 Java 版本中,您都可以這樣做:
Double[] orange = {11.7, 0.9, 0.1, 4.0, 89.0, 1.0, 0.0, 1.0, 2.0, 0.1, 4.0, 5.0, 47.0};
Double[] broccoli = {7.2, 2.4, 0.4, 31.0,108.0, 7.0,176.0,30.0, 45.0, 23.0, 4.0, 3.0, 11.0};
String[] keys = {"orange", "broccoli"};
Double[][] values = {orange , broccoli };
Map<String, Double[]> map = new HashMap<>();
for (int i = 0; i < keys.length; i++)
map.put(keys[i], values[i]);
在 Java 9+ 中,如果你有 10 個或更少的映射條目,你可以像這樣簡化它:
Double[] orange = {11.7, 0.9, 0.1, 4.0, 89.0, 1.0, 0.0, 1.0, 2.0, 0.1, 4.0, 5.0, 47.0};
Double[] broccoli = {7.2, 2.4, 0.4, 31.0,108.0, 7.0,176.0,30.0, 45.0, 23.0, 4.0, 3.0, 11.0};
Map<String, Double[]> map = Map.of(
"orange" , orange,
"broccoli", broccoli );
如果你不需要Double[]被命名,你可以內(nèi)聯(lián)它們:
Map<String, Double[]> map = Map.of(
"orange", new Double[] {11.7, 0.9, 0.1, 4.0, 89.0, 1.0, 0.0, 1.0, 2.0, 0.1, 4.0, 5.0, 47.0},
"broccoli", new Double[] {7.2, 2.4, 0.4, 31.0,108.0, 7.0,176.0,30.0, 45.0, 23.0, 4.0, 3.0, 11.0} );

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個贊
您可以創(chuàng)建包含name和(列表)的類nutrients:
import java.util.*;
public class Main {
public static void main(String[] args) {
Fruit orange = new Fruit(
"orange",
new Double[]{0.9, 0.1, 4.0, 89.0, 1.0, 0.0, 1.0, 2.0, 0.1, 4.0, 5.0, 47.0}
);
Fruit broccoli = new Fruit(
"broccoli",
new Double[]{7.2, 2.4, 0.4, 31.0, 108.0, 7.0, 176.0, 30.0, 45.0, 23.0, 4.0, 3.0, 11.0}
);
List<Fruit> fruitList = new ArrayList<>(Arrays.asList(orange, broccoli));
Map<String, Double[]> map = new HashMap<>();
for (Fruit fruit : fruitList) {
map.put(fruit.getName(), fruit.getNutrients());
}
}
}
class Fruit {
private String name;
private Double[] nutrients;
Fruit(String name, Double[] nutrients) {
this.name = name;
this.nutrients = nutrients;
}
public String getName() {
return name;
}
public Double[] getNutrients() {
return nutrients;
}
}

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個贊
直到 Java-8,Java API 還沒有提供標(biāo)準(zhǔn)方法來放置多個鍵值而不需要put
多次使用方法。但是 Java-9 API 提供了一個工廠方法Map#of
,您可以使用它通過傳遞鍵值來構(gòu)建您的地圖。
Map.of("<Key1>", "<Value1>", "<Key2>", "<Value2>");
注意:Map#of
返回一個不可變的映射。
添加回答
舉報(bào)