如何在Java的地图中允许重复的键?

问题描述 投票:0回答:5
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Map<String,Double> map=new LinkedHashMap<String,Double>();
        line=br.readLine();        
        while(!line.equals("End")) {
            String[]arr2=line.split(" ");
            String model=arr2[1];
            Double distance=Double.parseDouble(arr2[2]);
            map.put(model, distance);
            line=br.readLine();
        }

我试图打印所有重复的键和值。我的输入应该是奥迪15.3奥迪8.6宝马45结束当我尝试打印时,它只会给我(Audi 8.6和Bmw 45)。我需要打印两次audi!

java string linkedhashmap
5个回答
0
投票

您在地图中不能有重复的键。您能做的最好的事情就是在值中包含一个列表。即Map<String, List<Double>> map = new HashMap<String, List<Double>>();


0
投票

最佳方法是使用面向对象的编程。

创建新课程

class Result {
    String model;
    String distance;

    public Result(String model, String distance) {
        this.model = model;
        this.distance = distance;
    }
}

更改类型

来自

Map<String,Double> map = new LinkedHashMap<String,Double>();

至:

List<Result> list = new ArrayList<Result>();

更改添加方法

来自:

map.put(model, distance);

至:

list.add(Result(model, distance));

0
投票

您的映射声明看起来像Map<String, Double>,这意味着只能将一个Double值映射到String键。

您可以简单地将Double更改为List<Double>并将键映射到列表,然后您的情况如下:

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Map<String, List<Double>> map=new LinkedHashMap<>();
line=br.readLine(); 
while(!line.equals("End")) {
    String[] arr2=line.split(" ");
    String model=arr2[1];
    Double distance=Double.parseDouble(arr2[2]);
    List<Double> distances = map.computeIfAbsent(model, key -> new ArrayList<>());
    distances.add(distance);
    line=br.readLine();
}

此结构更正确,意味着模型Audi具有不同距离的列表。键一Audi和值列表。


0
投票

在简单的Java映射中不能有重复的键。一种方法是使用它来保存List值而不是单个值,并在打印结果时遍历它们:

BufferedReader be = new BufferedReader(new InputStreamReader(System.in));
Map<String, List<Double>> map = new LinkedHashMap<>();
line=br.readLine();        
while(!line.equals("End")) {
    String[] arr2 = line.split(" ");
    String model = arr2[1];
    Double distance = Double.parseDouble(arr2[2]);
    map.computeIfAbsent(model, m -> new LinkedList<>()).add(distance);
    line = br.readLine();
}

然后,当您打印出来时:

for (Map.Entry<String, List<Double>> entry : map) {
    for (Double d : entry.getValue()) {
        System.out.println(entry.getKey() + " " d);
    }
}

0
投票

使用这样的地图Map<String, List<Double>>。这样,每个键可以有多个值。您的Audi示例将如下所示:

Map<String, List<Double>> map = new HashMap<>();
map.put("Audi", new ArrayList<>());
map.get("Audi").add(15.3);
map.get("Audi").add(8.6);

编辑

这也是添加if语句时的外观:

if (map.get(model) == null) {
    map.put(model, new ArrayList<>());
    map.get(model).add(distance);
} else {
    map.get(model).add(distance);           
}
© www.soinside.com 2019 - 2024. All rights reserved.