Pair in java example

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.

Читайте также:  Wysiwyg html offline редактор

Drop me your questions related to working with name-value pairs in Java.

Источник

Pair in Java

Java Course - Mastering the Fundamentals

A Pair is a really useful data structure which is used to store two values together. Pairs are useful when we need to return two values from a method which are associated with each other such as a Student name and marks, a number and its square, etc.

Java supports the Pair data structure using the Pair class available in javafx.util package post Java 8. Pair class in Java stores paired data in a key-value pair combination, this combination is also known as tuple.

Introduction to Java Pair Class

Since Java 8, Java provides a Pair class to store a pair of values together. These two values can be of any data type independent of each other. For example, one value can be of String type, and the second one can be an Integer .

Now, let’s see how we can use the in-built Pair class in Java.

1. Importing Pair class

For importing Pair class in Java we use:

2. Declaring a Pair object

Let us now see how to declare a Pair object in Java.

As a result of this statement, a Pair object of the type is created. The constructor will take the value 7 and Hello and store them in the Pair object pr .

3. Accessing values

Using getKey() and getValue() methods we can access the two values stored in a Pair object.

  1. getKey(): gets the first value.
  2. getValue(): gets the second value

Now, let’s see an example of implementing Pair class in Java.

Explanation:

As we can see, using the getKey() method, we can access the first value in the pair and using the getValue() method, we can access the second value. Both these methods are defined in the Pair class to access the first and second field values of a Pair object.

Here, simply refers to a pair of values that are stored together.

Do not confuse it with the used in a HashMap or HashTable .

Methods Provided by the javafx.util.Pair Class

Pair class in Java contains methods which make it easier to operate on Pair objects. Let’s see some of these methods, their use cases and how to implement them in our Java programs.

1. boolean equals()

Two Pair objects are said to be equal if and only if the corresponding keys and values in both objects are equal. equals() performs a deep comparison which means only the basic values need to be equal.

Читайте также:  Add points in php

Declaration:

2. String toString()

toString() method returns a String representation of a Pair object. toString() method in Pair class overrides the toString() method defined in Object class and returns a String view of the Pair object. The default name/value delimiter ‘=’ is always used between the key and value of the Pair object.

Declaration:

3. getKey() Method

This method returns the key for the given specific pair in Java and is declared as:

4. getValue() Method

This method returns value for the given pair in Java and is declared as:

Example to understand the `getValue()« method of Pair class in Java:

5. int hashCode()

This method generates a hash code for the given pair in Java, which is calculated using the key and value associated with the Pair object. This method overrides the hashCode() method declared in the Object class.

Declaration:

Note: The hashCode values for pair1 and pair2 are the same as the key, value are the same in both Pair objects.

Table for Pair Class Methods

Method Return Type Description
getKey() K Returns the key of the pair.
getValue() V Returns the value of the pair.
hashCode() int Generates a hash code for the given pair. Hashcode for equal Pair objects will be the same.
toString() String String representation of the pair.
equals(Object o) boolean If the object is not a Pair object or is null , equals() method returns false

Types of Pair Classes

  1. MutablePair Class: Mutable classes allow the value to be altered at any time during our program. getters and setters methods can be used to alter and access the value of a given object after being defined.

MutablePair is defined in the Apache Commons Lang which is why before using it in our program we have to make sure the package has been added to the classpath.

We can add the below dependencies section of pom.xml if we’re using Maven.

Maven is a build automation tool used primarily for Java projects.

How to import:

Creating MutablePair objects:

Update Values:

Accessing Elements:

  1. ImmutablePair Class: In the ImmutablePair class we cannot change the value of an object once it’s defined, it remains constant and the setValue() method cannot be used to alter the constant value.

Since ImmutablePair is also defined in the Apache Commons Lang, we need to add the package and import the same way we did in MutablePair .

Let’s see how we can create an ImmutablePair object:

Accessing Elements:

Now let’s implement ImmutablePair class in Java program.

Why do We Need Pair Class?

The following are a few cases when we need to use the Pair class:

  1. The Pair class in Java is used for managing a pair of values which are somehow associated with each other, for example, a player and score, a student and marks, etc.
  2. We can use a pair class in Java for returning a pair of values from a method.
  3. Pair class is especially useful while performing operations on a Tree . When we perform recursion on a tree data structure, it becomes easy to return values to the tree nodes towards the top with certain computations performed on them like a max or min operation on the subtree of a tree node.
Читайте также:  Call all method python

Custom Pair class in Java

We can create a Generic Pair class in Java with Java Generics. Generics means the data types will be dynamic or parameterized types. The data type of the member fields used inside a class will be provided in the class declaration.

Here we have created a Generic class which specifies the types of its member fields in its declaration.

Object Creation:

In a similar way, we can design a custom Pair class in Java using Java Generics. The Pair class will have its own public constructor for instantiation as we have seen above.

We can define two data fields in the Pair class i.e. first and second . The data types of first and second data fields will be defined in the Pair class declaration as shown in the code below.

We can define additional methods such as:

  • getKey() : To retrieve the values of first data field.
  • getValue() : To retrieve the values of second data field.
  • toString() : To return a String presentation of a Pair object.

Explanation:

  • Here we have implemented a custom generic Pair class with standard methods implemented inside them.
  • Then we have created a method getManOfTheMatch() to find out the maximum scorer and return the name of the player and score with it.
  • As it is visible in the data, Dhoni is the maximum scorer with the total score of 99 . Hence, its the output.

Conclusion

  1. Pair class in Java stores paired data in a key-value pair combination.
  2. We use the parameterized constructor provided by the javafx.util.Pair class to create a Pair object containing two associated values.
  3. There are various in-built methods provided by the Pair class such as getKey() , getValue() , equals() , toString() and hashCode() to perform various operations on Pair objects and retrieve their values.
  4. There are two types of pair classes, ImmutablePair and MutablePair classes.
  5. The Pair class in Java is used for managing key to value association, returning multiple values, and performing operations on Tree data structure.
  6. Using Java Generics, we can define a custom Pair class with necessary in-built methods such as given below. We can also define other methods as per certain specific requirements such as a method to find the maximum of two Pair objects.

Источник

Pair in java example

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

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 RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью