如何在Java中允许映射(Map)中存在重复的键?

huangapple 未分类评论52阅读模式
英文:

How to allow duplicate keys in map in java?

问题

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();
}
// Im trying to print all the keys and values although they are duplicate.
// My input should be
// Audi 15.3
// Audi 8.6
// BMW 45
// End

// And when im trying to print it, it gives me only (Audi 8.6 and Bmw 45).
// I need to print twice audi!
英文:
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Map&lt;String,Double&gt; map=new LinkedHashMap&lt;String,Double&gt;();
        line=br.readLine();        
        while(!line.equals(&quot;End&quot;)) {
        	String[]arr2=line.split(&quot; &quot;);
        	String model=arr2[1];
        	Double distance=Double.parseDouble(arr2[2]);
        	map.put(model, distance);
        	line=br.readLine();
        }

<br>Im trying to print all the keys and values although they are duplicate.
<br>My input should be
<br>Audi 15.3
<br>Audi 8.6
<br>BMW 45
<br>End
<br><br> And when im trying to print it, it gives me only (Audi 8.6 and Bmw 45).
<br>I need to print twice audi!

答案1

得分: 0

你不能在地图中拥有重复的键。最好的做法是在值中使用类似列表的结构。例如:Map<String, List<Double>> map = new HashMap<String, List<Double>>();

英文:

You can't have duplicate keys in a map. The best you can do is have something like a list in the values. i.e. Map&lt;String, List&lt;Double&gt;&gt; map = new HashMap&lt;String, List&lt;Double&gt;&gt;();

答案2

得分: 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(new Result(model, distance));
英文:

The best approach is using object-oriented programming.

Create new class

class Result {
    String model;
    String distance;

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

Change type of

from

Map&lt;String,Double&gt; map = new LinkedHashMap&lt;String,Double&gt;();

to:

List&lt;Result&gt; list = new ArrayList&lt;Result&gt;();

Change adding method

from:

map.put(model, distance);

to:

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

答案3

得分: 0

你的 Map 声明看起来像是 Map&lt;String, Double&gt;,这意味着只能将一个 Double 值映射到 String 键。

你可以简单地将 Double 更改为 List&lt;Double&gt; 并将一个键映射到列表,然后你的情况看起来像是:

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

这种结构更正确,意味着模型 Audi 有一个包含不同距离的列表。键是 Audi,对应的值是列表。

英文:

You Map declaration looks like Map&lt;String, Double&gt; that means, that only one Double value can be mapped to String key.

You can simply, change Double to List&lt;Double&gt; and map a key to the list, then your case look like:

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

This structure more correct, meaning the model Audi has a list of different distances. Key one Audi and list of values.

答案4

得分: 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);
    }
}
英文:

You can't have duplicate keys in a straight-forward Java map. One approach you can use it to hold a List of values instead of a single value, and iterate over them when you're printing out the results:

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

And then, when you print it out:

for (Map.Entry&lt;String, List&lt;Double&gt;&gt; entry : map) {
    for (Double d : entry.getValue()) {
        System.out.println(entry.getKey() + &quot; &quot; d);
    }
}

答案5

得分: -1

这不是我最喜欢做的事情,但是有一种方法可以在Map中允许重复项。你正在使用的LinkedHashMap使用了Object中定义的hashCode方法。
你可以创建一个围绕String的包装类,而无需覆盖equals和hashCode的默认实现。这将允许你向集合中添加“重复项”,因为Java认为它们不是相同的。

示例类:

public class StringWrapper {
   private String value;

   public StringWrapper(String value) {
      this.value = value;
   }

   // 获取器和设置器
   // 没有equals和hashcode
}
英文:

It's not my favourite thing to do, but there is a workaround to allow duplicates in a Map. The LinkedHashMap you are using, uses the hashCode method defined in Object.
You could create a wrapper class around String, without overriding the default implementation of equals and hashCode. This would allow you to add "duplicates" to your collection, because Java thinks they are not identical.

Example class:

public class StringWrapper {
   private String value;

   public StringWrapper(String value) {
      this.value = value;
   }

// getters and setters
// no equals and hashcode
}

huangapple
  • 本文由 发表于 2020年4月10日 19:01:38
  • 转载请务必保留本文链接:https://java.coder-hub.com/61138932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定