A Java collection of value pairs? (tuples?)

后端 未结 19 2742
名媛妹妹
名媛妹妹 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条回答
  •  猫巷女王i
    2020-11-22 05:47

    Apache common lang3 has Pair class and few other libraries mentioned in this thread What is the equivalent of the C++ Pair in Java?

    Example matching the requirement from your original question:

    List> myPairs = new ArrayList>();
    myPairs.add(Pair.of("val1", 11));
    myPairs.add(Pair.of("val2", 17));
    
    //...
    
    for(Pair pair : myPairs) {
      //following two lines are equivalent... whichever is easier for you...
      System.out.println(pair.getLeft() + ": " + pair.getRight());
      System.out.println(pair.getKey() + ": " + pair.getValue());
    }
    

提交回复
热议问题