-3

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!

3 Answers3

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

}
nbrooks
  • 18,126
  • 5
  • 54
  • 66
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
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
  • 1
    I 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