A Java collection of value pairs? (tuples?)

后端 未结 19 2323
名媛妹妹
名媛妹妹 2020-11-22 05:43

I like how Java has a Map where you can define the types of each entry in the map, for example .

What I\'m looking for is a type

相关标签:
19条回答
  • 2020-11-22 06:02

    To anyone developing for Android, you can use android.util.Pair. :)

    0 讨论(0)
  • 2020-11-22 06:05

    Expanding on the other answers a generic immutable Pair should have a static method to avoid cluttering your code with the call to the constructor:

    class Pair<L,R> {
          final L left;
          final R right;
    
          public Pair(L left, R right) {
            this.left = left;
            this.right = right;
          }
    
          static <L,R> Pair<L,R> of(L left, R right){
              return new Pair<L,R>(left, right);
          }
    }
    

    if you name the static method "of" or "pairOf" the code becomes fluent as you can write either:

        list.add(Pair.of(x,y)); // my preference
        list.add(pairOf(x,y)); // use with import static x.y.Pair.pairOf
    

    its a real shame that the core java libraries are so sparse on such things that you have to use commons-lang or other 3rd parties to do such basic stuff. yet another reason to upgrade to scala...

    0 讨论(0)
  • 2020-11-22 06:07

    Apache Crunch also has a Pair class: http://crunch.apache.org/apidocs/0.5.0/org/apache/crunch/Pair.html

    0 讨论(0)
  • 2020-11-22 06:07

    I mean, even though there is no Pair class in Java there is something pretty simmilar: Map.Entry

    Map.Entry Documentation

    This is (simplifying quite a bit) what HashMap , or actually any Map stores.

    You can create an instance of Map store your values in it and get the entry set. You will end up with a Set<Map.Entry<K,V>> which effectively is what you want.

    So:

    public static void main(String []args)
    {    
        HashMap<String, Integer> values = new HashMap<String,Integer>();
        values.put("A", 235);//your custom data, the types may be different
        //more data insertions....
        Set<Map.Entry<String,Integer>> list = values.entrySet();//your list 
        //do as you may with it
    }
    
    0 讨论(0)
  • 2020-11-22 06:09

    I was going to ask if you would not want to just use a List<Pair<T, U>>? but then, of course, the JDK doesn't have a Pair<> class. But a quick Google found one on both Wikipedia, and forums.sun.com. Cheers

    0 讨论(0)
  • 2020-11-22 06:09

    What about com.sun.tools.javac.util.Pair?

    0 讨论(0)
提交回复
热议问题