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!
您在地图中不能有重复的键。您能做的最好的事情就是在值中包含一个列表。即Map<String, List<Double>> map = new HashMap<String, List<Double>>();
最佳方法是使用面向对象的编程。
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));
您的映射声明看起来像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
和值列表。
在简单的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);
}
}
使用这样的地图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);
}