2

I have different elements of different types such as:

<0, "none">, <0, "constructor">, <0, "none">, <0, "method">, <1, "method">, <2, "constructor">, <2, "method">, <2, "constructor">

I would like to store them in a map or any other data structure without removing duplicates. I implemented the map as the following:

Map<Integer, String> m1 = new HashMap<>();
m1.put(0, "none");
m1.put(0, "constructor");
m1.put(1, "none");
m1.put(0, "method");

The result of printing m1 is {0=method, 1=method, 2=constructor} which I don't want. I want to show all the elements.

Adam Amin
  • 1,406
  • 2
  • 11
  • 23
  • what about `Map>`? – Akash Shah Mar 25 '19 at 12:40
  • The point of a `Map` is to achieve lookup via the key. That does not seem to be your purpose here. What is your purpose? Just to have a set to iterate over? – Stewart Mar 25 '19 at 12:44
  • Have you look at https://stackoverflow.com/questions/521171/a-java-collection-of-value-pairs-tuples ? –  Mar 25 '19 at 12:45

3 Answers3

5

Create an object like below,

public class MyData {
private int id;
private String type;
// Constructor
// getters and setters
}

Then create MyData objects and store it in a list,

List<MyData> myData = new ArrayList<MyData>();

MyData data1 = new MyData(0, "none"); 
MyData data2 = new MyData(1, "method"); 
MyData data3 = new MyData(2, "constructor"); 
MyData data4 = new MyData(0, "none");

myData.add(data1); 
myData.add(data1); 
myData.add(data1); 
myData.add(data1);
Santosh
  • 874
  • 11
  • 21
3

Guava has a multimap class that's perfect for this type of problem. Take a look at multimap.

jwismar
  • 12,164
  • 3
  • 32
  • 44
0

The key in Map must be unique, so once you call m1.put(0, "constructor");, you replace the previous value mapped to 0, which was "none". Either use multimap (Map<Integer,List<String>>), or use list/set of Pairs.

Ondra K.
  • 2,767
  • 4
  • 23
  • 39