如何在使用地图时避免重复使用put()方法?

问题描述 投票:-1回答:3

基本上我有这个HashMap:

HashMap<String, Double[]> list = new HashMap<>();

和价值观(我想要保存的食物的宏观和微量营养素):

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};

list.put("orange", orange);

list.put("broccoli", broccoli);

现在我有更多的食物,所以我想把所有“list.put()”缩小为一个。也许使用for循环。并使用带有食物名称的另一个String数组来迭代每个。关于如何组织我想要做的事情的任何提示?谢谢。

如果需要,我的其余代码就在这里:https://pastebin.com/Vw2UerDG

java list hashmap put repeating
3个回答
1
投票

在任何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[],你可以内联它们:

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} );

0
投票

直到Java-8,Java API没有提供标准方法来放置多个键值而不使用put方法多次。但是Java-9 API提供了一个工厂方法Map#of,你可以使用它通过传递键值来构建你的地图。

Map.of("<Key1>", "<Value1>", "<Key2>", "<Value2>");

注意:Map#of返回一个不可变的映射。


0
投票

您可以创建包含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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.