I need a data structure in java that can store 1 key and 2 pair values. 1 value needs to be a string and the other an int. I will also need to be able to put in and take out values and sort the pairs according to the int value. Please help!
Asked
Active
Viewed 53 times
-3
-
3If you encapsulate that (String, int) pair into a meaningful class you can use a Map. – duffymo Sep 27 '16 at 11:59
-
Possible duplicate of [HashMap: One Key, multiple Values](http://stackoverflow.com/questions/8229473/hashmap-one-key-multiple-values) – But I'm Not A Wrapper Class Sep 27 '16 at 12:00
-
Probably you may want to have a look over MultiMap(Google Guava library).Java standard development kit hasn't got MultiMap kind of data structure – Ankit Tripathi Sep 27 '16 at 12:01
-
1No, this isn't a MultiMap. That means multiple values of the same type; these are different types. – duffymo Sep 27 '16 at 12:33
3 Answers
1
Let's break it down to what you need:
1. you need something that store key->value, hence use Map
2. The key is String, no problem here.
3. the value is string/int pair, you can create such class:
public class MyPair {
private String s;
private int i;
public MyPair(String s, int i) {
this.s = s;
this.i = i;
}
// ommitting getters, hashcode and toString
}
4. You need it to be sorted by the int, so use Comparable
interface:
public class MyPair implements Comparable<MyPair> {
private String s;
private int i;
public MyPair(String s, int i) {
this.s = s;
this.i = i;
}
public int compareTo(MyPair other) {
return this.i - other.i;
}
// ommiting getters, hashcode and toString
}
1
Either you use wrapper as mentioned in the other answers or you can use 2 maps one for the string and one for the Integer.

Amer Qarabsa
- 6,412
- 3
- 20
- 43
-
Surely the first one is preferred. If the two items are related, it's better to encapsulate them together rather than maintaining two data structures. – duffymo Sep 27 '16 at 12:34
-
1I could not agree more, yet it is still an option depending on the case – Amer Qarabsa Sep 27 '16 at 12:38
0
public class Option{
private Integer id;
private String value;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
make class and use

nbrooks
- 18,126
- 5
- 54
- 66

Tom jaison
- 205
- 3
- 12