Pairs in Java
Learn to work with key value pairs in Java using Pair classes e.g. javafx.util.Pair , ImmutablePair , MmutablePair (common langs) and io.vavr.Tuple2 class.
A pair provide a convenient way of associating a simple key to value. In Java, maps are used to store key-value pairs. Maps store a collection of pairs and operate them as a whole.
Sometimes, we need to work on requirements where a key-value pair shall exist on it’s own. e.g.
- A pair need to be passed in a method as argument
- Method need to return two values in form of a pair
Java core APIs have javafx.util.Pair as closest match which serve the purpose of having two values as name-value pair. Follow this link to learn to add JavaFx support in eclipse.
Pair class provides following methods.
- boolean equals(Object o) – Test this Pair for equality with another Object.
- K getKey() – Gets the key for this pair.
- V getValue() – Gets the value for this pair.
- int hashCode() – Generate a hash code for this Pair.
- String toString() – String representation of this Pair.
Let’s see a java program to create and use pair.
Pair pair = new Pair<>(100, "howtodoinjava.com"); Integer key = pair.getKey(); //100 String value = pair.getValue(); //howtodoinjava.com pair.equals(new Pair<>(100, "howtodoinjava.com")); //true - same name and value pair.equals(new Pair<>(222, "howtodoinjava.com")); //false - different name pair.equals(new Pair<>(100, "example.com")); //false - different value
3. Pair, ImmutablePair and MutablePair – Apache commons lang
Commons lang library has a useful class which can used as pair i.e. org.apache.commons.lang3.tuple.Pair. It has two subclasses which can also be used for same purpose i.e. ImmutablePair and MutablePair.
- Pair class is a pair consisting of two elements.
- Pair refers to the elements as ‘left’ and ‘right’.
- Pair also implements the Map.Entry interface where the key is ‘left’ and the value is ‘right’.
- ImmutablePair is immutable representation on Pair . If mutable objects are stored in the pair, then the pair itself effectively becomes mutable. The class is also not final , so a subclass could add undesirable behavior.
- ImmutablePair is thread-safe if the stored objects are thread-safe.
ImmutablePair pair = ImmutablePair.of(100, "howtodoinjava.com"); Integer key = pair.getKey(); //100 String value = pair.getValue(); //howtodoinjava.com //Integer key = pair.getLeft(); //100 //String value = pair.getRight(); //howtodoinjava.com pair.equals(ImmutablePair.of(100, "howtodoinjava.com")); //true - same name and value pair.equals(ImmutablePair.of(222, "howtodoinjava.com")); //false - different name pair.equals(ImmutablePair.of(100, "example.com")); //false - different value
Do not forget to import the library into application classpath.
org.apache.commons commons-lang3 3.8.1
Another useful class for storing key-value pair is Tuple2.
Tuple2 provide lots of useful method to work on data stored in it. e.g.
- T1 _1() – Getter of the 1st element of this tuple.
- T2 _2() – Getter of the 2nd element of this tuple.
- Tuple2 update1(T1 value) – Sets the 1st element of this tuple to the given value.
- Tuple2 update2(T2 value) – Sets the 2nd element of this tuple to the given value.
- Map.Entry toEntry() – Converts the tuple to java.util.Map.Entry Tuple.
- Tuple2 swap() – Swaps the elements of this Tuple.
- Tuple2 map(BiFunction mapper) – Maps the components of this tuple using a mapper function.
- int compareTo(Tuple2 that) – Compare two Tuple2 instances.
Tuple2 pair = new Tuple2<>(100, "howtodoinjava.com"); Integer key = pair._1(); //100 String value = pair._2(); //howtodoinjava.com pair.equals(new Tuple2<>(100, "howtodoinjava.com")); //true - same name and value pair.equals(new Tuple2<>(222, "howtodoinjava.com")); //false - different name pair.equals(new Tuple2<>(100, "example.com")); //false - different value
Do not forget to import the library into application classpath.
Drop me your questions related to working with name-value pairs in Java.
Реализовать класс Pair в Java
В этом посте мы обсудим, как реализовать наш собственный класс Pair в Java.
Пара — это контейнер для хранения кортежа из двух объектов. JDK не предоставляет какой-либо реализации класса Pair. Это может быть связано с тем, что класс Pair не определяет связь между указанными значениями. Возьмем пример std::pair в C++, где его first а также second поля могут быть любыми. C++ не указывает, какие данные pair классные магазины. В Java, Map.Entry — отличный пример со значимым именем, представляющим пару ключ-значение.
Несмотря на отсутствие какой-либо значимой связи между данными, хранящимися в паре, программисты часто упускают эту функцию в Java. Есть обходные пути, как обсуждалось здесь, подробно, чтобы восполнить пробел. Но было бы здорово реализовать наш собственный класс Pair на Java, который мы могли бы настроить в соответствии со своим стилем.
На самом деле написать класс Pair на Java очень просто. Ниже приведена простая пользовательская реализация класса Pair в Java, которая имеет
- Два публичных поля – first а также second , как и в C++.
- Частный конструктор.
- Статический фабричный метод of() для создания неизменного, типизированного Pair экземпляр (который внутренне вызывает частный конструктор).
- Переопределенные методы hashCode() и equals() к обеспечить желаемое поведение в коллекциях на основе хэшей.
- Переопределено toString() способ легко распечатать Pair объект.
Следующая программа демонстрирует это:
Java string pair array
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter