Home >Java >javaTutorial >How Can I Create and Manage Collections of Value Pairs in Java Without Using Maps?
Java Collections for Value Pairs
In Java, a Map provides a data structure for storing key-value pairs with defined types. However, the desire for a collection of value pairs without the key-based structure arises.
To achieve this, consider using the AbstractMap.SimpleEntry class. It allows the creation of simple value pairs, each with its own specified type.
Creating and Adding Pairs
To create a list of these value pairs, initialize an ArrayList of Map.Entry
Map.Entry<String, Integer> pair1 = new AbstractMap.SimpleEntry<>("Not Unique key1", 1); Map.Entry<String, Integer> pair2 = new AbstractMap.SimpleEntry<>("Not Unique key2", 2); pairList.add(pair1); pairList.add(pair2);
Enhancing Verbosity
To reduce verbosity, employ a createEntry method:
pairList.add(createEntry("Not Unique key1", 1)); pairList.add(createEntry("Not Unique key2", 2));
Syntactic Conciseness
Subclass ArrayList to implement an of method:
pair.of("Not Unique key1", 1); pair.of("Not Unique key2", 2);
With AbstractMap.SimpleEntry, you can create collections of ordered value pairs, providing a concise and type-safe solution for storing pairs of values.
The above is the detailed content of How Can I Create and Manage Collections of Value Pairs in Java Without Using Maps?. For more information, please follow other related articles on the PHP Chinese website!