A Java collection of value pairs? (tuples?)

后端 未结 19 2338
名媛妹妹
名媛妹妹 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:00

    What about "Apache Commons Lang 3" Pair class and the relative subclasses ?

        import org.apache.commons.lang3.tuple.ImmutablePair;
        import org.apache.commons.lang3.tuple.Pair;
        ...
        @SuppressWarnings("unchecked")
        Pair[] arr = new ImmutablePair[]{
                ImmutablePair.of("A", 1),
                ImmutablePair.of("B", 2)};
    
        // both access the 'left' part
        String key = arr[0].getKey();
        String left = arr[0].getLeft();
    
        // both access the 'right' part
        Integer value = arr[0].getValue();
        Integer right = arr[0].getRight();
    

    ImmutablePair is a specific subclass that does not allow the values in the pair to be modified, but there are others implementations with different semantic. These are the Maven coordinates, if you need them.

            
                org.apache.commons
                commons-lang3
                3.4
            
    

提交回复
热议问题