Implement Pair Class with Unit Class in Java using JavaTuples
Following are the ways to implement Pair Class with Unit Class
- Using direct values
import
java.util.*;
import
org.javatuples.*;
class
GfG {
public
static
void
main(String[] args)
{
// Create a Unit
Unit<String> unit =
new
Unit<String>(
"GeeksforGeeks"
);
// print unit
System.out.println(
"Unit: "
+ unit);
// create Pair from Unit
Pair<Integer, String>
pair =
new
Pair<Integer, String>(
Integer.valueOf(
1
), unit.getValue0());
// Print the Pair
System.out.println(
"Pair: "
+ pair);
}
}
chevron_rightfilter_noneOutput:
Unit: [GeeksforGeeks] Pair: [1, GeeksforGeeks]
- Using Unit.add() method
// Below is a Java program to demonstrate
// use of add() method with
// single value
import
java.util.*;
import
org.javatuples.*;
class
GfG {
public
static
void
main(String[] args)
{
// Using with() method to instantiate unit object
Unit<String> unit = Unit.with(
"Geeks"
);
// print unit
System.out.println(
"Unit: "
+ unit);
// Using add() to create Pair
Pair<String, String> pair = unit.add(
"forGeeks"
);
// Print the Pair
System.out.println(
"Pair: "
+ pair);
}
}
chevron_rightfilter_noneOutput:
Unit: [Geeks] Pair: [Geeks, forGeeks]
- Using Unit.addAtX() method
- Program 1: Adding Unit at Position 0 using addAt0()
// Below is a Java program to demonstrate
// use of addAt0() method with
// direct value
import
java.util.*;
import
org.javatuples.Unit;
import
org.javatuples.Pair;
class
GfG {
public
static
void
main(String[] args)
{
// Using with() method to instantiate unit object
Unit<String> unit = Unit.with(
"Geeks"
);
// print unit
System.out.println(
"Unit: "
+ unit);
// Using addAtX() to create Pair
Pair<String, String> pair = unit.addAt0(
"forGeeks"
);
// Print the Pair
System.out.println(
"Pair: "
+ pair);
}
}
chevron_rightfilter_noneOutput:
Unit: [Geeks] Pair: [forGeeks, Geeks]
- Program 2: Adding Unit at Position 1 using addAt1()
// Below is a Java program to demonstrate
// use of addAt1() method with
// direct value
import
java.util.*;
import
org.javatuples.Unit;
import
org.javatuples.Pair;
class
GfG {
public
static
void
main(String[] args)
{
// Using with() method to instantiate unit object
Unit<String> unit = Unit.with(
"Geeks"
);
// print unit
System.out.println(
"Unit: "
+ unit);
// Using addAtX() to create Pair
Pair<String, String> pair = unit.addAt1(
"forGeeks"
);
// Print the Pair
System.out.println(
"Pair: "
+ pair);
}
}
chevron_rightfilter_noneOutput:
Unit: [Geeks] Pair: [Geeks, forGeeks]
- Program 1: Adding Unit at Position 0 using addAt0()
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.