A Java collection of value pairs? (tuples?)

后端 未结 19 2326
名媛妹妹
名媛妹妹 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: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 {
          final L left;
          final R right;
    
          public Pair(L left, R right) {
            this.left = left;
            this.right = right;
          }
    
          static  Pair of(L left, R right){
              return new Pair(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...

提交回复
热议问题