📅  最后修改于: 2023-12-03 14:42:15.132000             🧑  作者: Mango
Sometimes in programming, there is a need to store data in pairs or key-value pairs. In Java, a pair can be represented using the Map.Entry
class. However, if we need to store multiple pairs, we can use a List of Pair.
To implement a List of Pair in Java, we can make use of the SimpleEntry
class in the java.util.AbstractMap
package. This class extends the AbstractMap.SimpleImmutableEntry
class and allows us to create a simple key-value pair.
List<Map.Entry<String, Integer>> pairs = new ArrayList<>();
pairs.add(new AbstractMap.SimpleEntry<>("John", 25));
pairs.add(new AbstractMap.SimpleEntry<>("Mary", 30));
We can also create a Pair class to represent a pair of values.
public class Pair<T, U> {
public final T first;
public final U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
}
With this class, we can create a List of Pair as follows:
List<Pair<String, Integer>> pairs = new ArrayList<>();
pairs.add(new Pair<>("John", 25));
pairs.add(new Pair<>("Mary", 30));
We can use the List of Pair in various scenarios. For example, to store the frequency of elements in a list.
List<String> list = Arrays.asList("John", "Mary", "John", "Mary", "Mary");
Map<String, Integer> frequency = new HashMap<>();
for (String str : list) {
frequency.put(str, frequency.getOrDefault(str, 0) + 1);
}
List<Map.Entry<String, Integer>> pairs = new ArrayList<>(frequency.entrySet());
In the above code, we first create a Map to store the frequency of elements in the list. We then create a List of Pair from the entrySet of the Map.
In this article, we learned how to implement and use a List of Pair in Java. This data structure can be very useful in various scenarios where we need to store data in pairs.