En C++ tenemos std::par en la biblioteca de utilidades, que es de inmensa utilidad si queremos mantener un par de valores juntos. Estábamos buscando una clase equivalente para par en Java, pero la clase Par no apareció hasta Java 7. JavaFX 2.2 tiene la javafx.util.Par clase que se puede utilizar para almacenar un par. Necesitamos almacenar los valores en Pair usando el constructor parametrizado proporcionado por javafx.util.Par clase.
Nota: Tenga en cuenta que el par se utiliza en HashMap/TreeMap. Aquí, simplemente se refiere a un par de valores que se almacenan juntos.
Métodos proporcionados por la clase javafx.util.Pair
Sintaxis: La clase de par en el método Java.
Pair var_name = new Pair(key, value);>
- Par (tecla K, valor V): Crea un nuevo par.
- booleano es igual(): Se utiliza para comparar dos pares de objetos. Realiza una comparación profunda, es decir, compara en función de los valores () que están almacenados en los objetos del par.
Ejemplo:
Java
Pair p1 => new> Pair(> 3> ,> 4> );> Pair p2 => new> Pair(> 3> ,> 4> );> Pair p3 => new> Pair(> 4> ,> 4> );> System.out.println(p1.equals(p2) + + p2.equals(p3));> |
>
>
Producción:
true false>
- Cadena a Cadena(): Este método devolverá la representación de cadena del par.
- K obtenerClave(): Devuelve la clave del par.
- V obtenerValor(): Devuelve un valor para el par.
- int código hash(): Genera un código hash para el par.
Accediendo a valores: Usando obtener la clave() y obtenerValor() métodos podemos acceder a los valores de un objeto Pair.
1. getKey(): obtiene el primer valor.
2. getValue(): obtiene el segundo valor
Nota: Aquí, se refiere a un par de valores que se almacenan juntos. No es como el par que se usa en Map.
Implementación:
Java
java reemplazar todo
imagen central en css
// Java program to implement in-built pair classes> import> javafx.util.Pair;> class> GFG {> > // Main driver method> > public> static> void> main(String[] args)> > {> > Pair p> > => new> Pair(> 10> ,> 'Hello Geeks!'> );> > // printing the values of key and value pair> > // separately> > System.out.println(> 'The First value is :'> > + p.getKey());> > System.out.println(> 'The Second value is :'> > + p.getValue());> > }> }> |
>
>
Echemos un vistazo al siguiente problema.
Planteamiento del problema : Nos dan los nombres de n estudiantes con sus correspondientes puntuaciones obtenidas en un cuestionario. Necesitamos encontrar al estudiante con la puntuación máxima en la clase.
Nota: Debe tener Java 8 instalado en su máquina para poder ejecutar el siguiente programa.
Java
// Java program to find a Pair which has maximum score> // Importing required classes> import> java.util.ArrayList;> import> javafx.util.Pair;> // class> class> Test {> > // This method returns a Pair which hasmaximum score> > public> static> Pair> > getMaximum(ArrayList l)> > {> > // Assign minimum value initially> > int> max = Integer.MIN_VALUE;> > // Pair to store the maximum marks of a> > // student with its name> > Pair ans> > => new> Pair(> ''> ,> 0> );> > // Using for each loop to iterate array of> > // Pair Objects> > for> (Pair temp : l) {> > // Get the score of Student> > int> val = temp.getValue();> > // Check if it is greater than the previous> > // maximum marks> > if> (val>máximo) {> > max = val;> // update maximum> > ans = temp;> // update the Pair> > }> > }> > return> ans;> > }> > // Driver method to test above method> > public> static> void> main(String[] args)> > {> > int> n => 5> ;> // Number of Students> > // Create an Array List> > ArrayList l> > => new> ArrayList();> > /* Create pair of name of student with their> > corresponding score and insert into the> > Arraylist */> > l.add(> new> Pair(> 'Student A'> ,> 90> ));> > l.add(> new> Pair(> 'Student B'> ,> 54> ));> > l.add(> new> Pair(> 'Student C'> ,> 99> ));> > l.add(> new> Pair(> 'Student D'> ,> 88> ));> > l.add(> new> Pair(> 'Student E'> ,> 89> ));> > // get the Pair which has maximum value> > Pair ans = getMaximum(l);> > System.out.println(ans.getKey() +> ' is top scorer '> > +> 'with score of '> > + ans.getValue());> > }> }> |
>
>
Producción:
Student C is top scorer with score of 99>
Nota: Es posible que el programa anterior no se ejecute en un IDE en línea; utilice un compilador fuera de línea.