Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

457
Vistas
Eliminar duplicados en matriz 2d

Quiero eliminar la fila duplicada en una matriz 2d. Probé el siguiente código, pero no funciona. por favor, ayúdame .

Aporte :

 1,ram,mech 1,ram,mech 2,gopi,csc 2.gopi,civil

la salida debe ser:

 1,ram,mech 2,gopi,csc 2.gopi,civil

Código:

 package employee_dup; import java.util.*; public class Employee_dup { public static void main(String[] args) { boolean Switch = true; System.out.println("Name ID Dept "); String[][] employee_t = {{"1","ram","Mech"},{"1","siva","Mech"},{"1","gopi","Mech"},{"4","jenkat","Mech"},{"5","linda","Mech"},{"1","velu","Mech"}}; int g = employee_t[0].length; String[][] array2 = new String[10][g]; int rows = employee_t.length; Arrays.sort(employee_t, new sort(0)); for(int i=0;i<employee_t.length;i++){ for(int j=0;j<employee_t[0].length;j++){ System.out.print(employee_t[i][j]+" "); } System.out.println(); } List<String[]> l = new ArrayList<String[]>(Arrays.asList(employee_t)); for(int k = 0 ;k < employee_t.length-1;k++) { if(employee_t[k][0] == employee_t[k+1][0]) { System.out.println("same value is present"); l.remove(1); array2 = l.toArray(new String[][]{}); } } System.out.println("Name ID Dept "); for(int i=0;i<array2.length;i++){ for(int j=0;j<array2[0].length;j++){ System.out.print(array2[i][j]+" "); } System.out.println(); } } } class sort implements Comparator { int j; sort(int columnToSort) { this.j = columnToSort; } //overriding compare method public int compare(Object o1, Object o2) { String[] row1 = (String[]) o1; String[] row2 = (String[]) o2; //compare the columns to sort return row1[j].compareTo(row2[j]); } }

Primero ordené la matriz en función de la columna uno, luego traté de eliminar los duplicados al verificar los elementos de la primera columna y los elementos de la segunda columna, pero no eliminó la columna requerida sino que eliminó otras columnas.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Puedes probar esta solución:

 public static void main(String[] args) { String[][] employee_t = { {"1","ram","Mech"}, {"1","ram","Mech"}, {"1","siva","Mech"}, {"1","siva","Mech"}, {"1","gopi","Mech"}, {"1","gopi","Mech"} }; System.out.println("ID Name Dept"); Arrays.stream(employee_t) .map(Arrays::asList) .distinct() .forEach(row -> System.out.printf("%-3s%-7s%s\n", row.get(0), row.get(1), row.get(2))); }

Producción

 ID Name Dept 1 ram Mech 1 siva Mech 1 gopi Mech

Cómo funciona: la comparación de matrices se basa en la igualdad de instancias y no en la comparación de elementos contenidos por equals . Por lo tanto, convertir cada fila de su matriz 2D en una List le permitirá comparar listas, lo que tiene en cuenta los elementos equals que contiene.

La Java Stream API proporciona un método distinct que se basa en equals y eliminará todos los duplicados por usted.

over 4 years ago · Santiago Trujillo Denunciar

0

Basado en su código. Tal vez no sea la MEJOR solución, pero funciona.

 public static void main(String[] args) { System.out.println("Name ID Dept "); // I added duplicated rows String[][] inputArray = { { "1", "ram", "Mech" }, { "1", "siva", "Mech" }, { "1", "gopi", "Mech" }, { "1", "gopi", "Mech" }, { "4", "jenkat", "Mech" }, { "5", "linda", "Mech" }, { "1", "velu", "Mech" }, { "1", "velu", "Mech" } }; // I will add all rows in a Set as it doesn't store duplicate values Set<String> solutionSet = new LinkedHashSet<String>(); // I get all rows, create a string and insert into Set for (int i = 0 ; i < inputArray.length ; i++) { String input = inputArray[i][0]+","+inputArray[i][1]+","+inputArray[i][2]; solutionSet.add(input); } // You know the final size of the output array String[][] outputArray = new String[solutionSet.size()][3]; // I get the results without duplicated values and reconvert it to your format int position = 0; for(String solution : solutionSet) { String[] solutionArray = solution.split(","); outputArray[position][0] = solutionArray[0]; outputArray[position][1] = solutionArray[1]; outputArray[position][2] = solutionArray[2]; position++; } System.out.println("Name ID Dept "); for (int i = 0; i < outputArray.length; i++) { for (int j = 0; j < outputArray[0].length; j++) { System.out.print(outputArray[i][j] + " "); } System.out.println(); } }
over 4 years ago · Santiago Trujillo Denunciar

0

He publicado lo que creo que es una solución legible y fácil de mantener.

Decidí usar distinct de Stream que es parte de Java 8

Devuelve una secuencia que consta de los distintos elementos (según Object.equals(Object)) de esta secuencia. - https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--

Clase principal

 class Main { public static void main(String[] args) { //Create a list of Employee objects List<Employee> employeeList = new ArrayList<Employee>(); Employee e1 = new Employee(1, "ram", "mech"); Employee e2 = new Employee(1, "ram", "mech"); Employee e3 = new Employee(2, "gopi", "csc"); Employee e4 = new Employee(2, "gopi", "civil"); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); System.out.println("Before removing duplicates"); employeeList.stream().forEach(System.out::println); //This is where all the magic happens. employeeList = employeeList.stream().distinct().collect(Collectors.toList()); System.out.println("\nAfter removing duplicates"); employeeList.stream().forEach(System.out::println); } }

Producción:

 Before removing duplicates Employee [valA=1, valB=ram, valC=mech] Employee [valA=1, valB=ram, valC=mech] Employee [valA=2, valB=gopi, valC=csc] Employee [valA=2, valB=gopi, valC=civil] After removing duplicates Employee [valA=1, valB=ram, valC=mech] Employee [valA=2, valB=gopi, valC=csc] Employee [valA=2, valB=gopi, valC=civil]

Empleado.clase

 //This is just a regular POJO class. class Employee { int valA; String valB, valC; public Employee(int valA, String valB, String valC){ this.valA = valA; this.valB = valB; this.valC = valC; } public Employee(Employee e) { this.valA = e.valA; this.valB = e.valB; this.valC = e.valC; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + valA; result = prime * result + ((valB == null) ? 0 : valB.hashCode()); result = prime * result + ((valC == null) ? 0 : valC.hashCode()); return result; } @Override public boolean equals(Object obj) { if(obj instanceof Employee && ((Employee)obj).hashCode() == this.hashCode()){ return true; } return false; } @Override public String toString() { return "Employee [valA=" + valA + ", valB=" + valB + ", valC=" + valC + "]"; } }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda