A Java collection of value pairs? (tuples?)

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

    This is based on JavaHelp4u 's code.

    Less verbose and shows how to do in one line and how to loop over things.

    //======>  Imports
    import java.util.AbstractMap.SimpleEntry;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map.Entry;
    
    //======>  Single Entry
    SimpleEntry myEntry = new SimpleEntry("ID", "Text");
    System.out.println("key: " + myEntry.getKey() + "    value:" + myEntry.getValue());
    System.out.println();
    
    //======>  List of Entries
    List> pairList = new ArrayList<>();
    
    //-- Specify manually
    Entry firstButton = new SimpleEntry("Red ", "Way out");
    pairList.add(firstButton);
    
    //-- one liner:
    pairList.add(new SimpleEntry("Gray", "Alternate route"));  //Ananomous add.
    
    //-- Iterate over Entry array:
    for (Entry entr : pairList) {
        System.out.println("Button: " + entr.getKey() + "    Label: " + entr.getValue());
    }
    

提交回复
热议问题