A Java collection of value pairs? (tuples?)

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

    AbstractMap.SimpleEntry

    Easy you are looking for this:

    java.util.List> pairList= new java.util.ArrayList<>();
    

    How can you fill it?

    java.util.Map.Entry pair1=new java.util.AbstractMap.SimpleEntry<>("Not Unique key1",1);
    java.util.Map.Entry pair2=new java.util.AbstractMap.SimpleEntry<>("Not Unique key2",2);
    pairList.add(pair1);
    pairList.add(pair2);
    

    This simplifies to:

    Entry pair1=new SimpleEntry<>("Not Unique key1",1);
    Entry pair2=new SimpleEntry<>("Not Unique key2",2);
    pairList.add(pair1);
    pairList.add(pair2);
    

    And, with the help of a createEntry method, can further reduce the verbosity to:

    pairList.add(createEntry("Not Unique key1", 1));
    pairList.add(createEntry("Not Unique key2", 2));
    

    Since ArrayList isn't final, it can be subclassed to expose an of method (and the aforementioned createEntry method), resulting in the syntactically terse:

    TupleList> pair = new TupleList<>();
    pair.of("Not Unique key1", 1);
    pair.of("Not Unique key2", 2);
    

提交回复
热议问题