Implement Apache Commons Library
In this step, we will learn how to use MutablePair and ImmutablePair classes from the Apache Commons library to create and manipulate pairs. Add the following code to your PairsInJava.java file:
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
public class PairsInJava {
public static void main(String[] args) {
MutablePair<String, Integer> p1 = new MutablePair<>("apple", 1);
ImmutablePair<String, Integer> p2 = new ImmutablePair<>("banana", 2);
System.out.println("p1=" + p1.getLeft() + "," + p1.getRight());
System.out.println("p2=" + p2.getLeft() + "," + p2.getRight());
p1.setLeft("orange");
p1.setRight(3);
System.out.println("new p1=" + p1.getLeft() + "," + p1.getRight());
// cannot set values for immutable pair
// p2.setLeft("kiwi");
p2 = p2.withLeft("kiwi");
System.out.println("new p2=" + p2.getLeft() + "," + p2.getRight());
}
}
In the code above, we use MutablePair and ImmutablePair classes from the Apache commons library to create pairs and then modify their key and value.
To compile and run the code, execute the following command:
javac -cp .:commons-lang3-3.13.0.jar PairsInJava.java && java -cp .:commons-lang3-3.13.0.jar PairsInJava