Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 删除二维阵列中的重复项_Java_Multidimensional Array_Duplicates - Fatal编程技术网

Java 删除二维阵列中的重复项

Java 删除二维阵列中的重复项,java,multidimensional-array,duplicates,Java,Multidimensional Array,Duplicates,我想删除二维数组中的重复行。我尝试了下面的代码。但它不起作用。请帮帮我 输入: 输出应为: 代码: 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 ");

我想删除二维数组中的重复行。我尝试了下面的代码。但它不起作用。请帮帮我

输入:

输出应为:

代码:

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]);
    }
}
package-employee\u-dup;
导入java.util.*;
公共类雇员{
公共静态void main(字符串[]args)
{
布尔开关=真;
System.out.println(“名称ID部门”);
字符串[][]employee_t={{“1”、“ram”、“Mech”}、{“1”、“siva”、“Mech”}、{“1”、“gopi”、“Mech”}、{“4”、“jenkat”、“Mech”}、{“5”、“linda”、“Mech”}、{“1”、“velu”、“Mech”};
int g=employee\u t[0]。长度;
字符串[][]数组2=新字符串[10][g];
int rows=员工长度;
排序(employee_t,新排序(0));

对于(int i=0;i您可以尝试此解决方案:

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)));
}
输出

ID Name   Dept
1  ram    Mech
1  siva   Mech
1  gopi   Mech
工作原理:比较数组依赖于实例相等,而不是通过
equals
比较包含的元素。因此,将2D数组的每一行转换为
列表
将使您能够比较列表,这将考虑包含的元素的
equals


Java流API
确实提供了一种方法
distinct
,该方法依赖于
equals
,并将为您删除所有重复项。

您可以尝试此解决方案:

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)));
}
输出

ID Name   Dept
1  ram    Mech
1  siva   Mech
1  gopi   Mech
工作原理:比较数组依赖于实例相等,而不是通过
equals
比较包含的元素。因此,将2D数组的每一行转换为
列表
将使您能够比较列表,这将考虑包含的元素的
equals


Java流API
确实提供了一种方法
distinct
,该方法依赖于
equals
,并将为您删除所有重复项。

基于您的代码。也许这不是最好的解决方案,但它是有效的

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();
    }

}
public static String[][] removeDuplicate(String[][] matrix) {
    String[][] newMatrix = new String[matrix.length][matrix[0].length];
    int newMatrixRow = 1;

    for (int i = 0; i < matrix[0].length; i++)
        newMatrix[0][i] = matrix[0][i];

    for (int j = 1; j < matrix.length; j++) {
        List<Boolean> list = new ArrayList<>();
        for (int i = 0; newMatrix[i][0] != null; i++) {
            boolean same = true;
            for (int col = 2; col < matrix[j].length; col++) {
                if (!newMatrix[i][col].equals(matrix[j][col])) {
                    same = false;
                    break;
                }
            }
            list.add(same);
        }

        if (!list.contains(true)) {
            for (int i = 0; i < matrix[j].length; i++) {
                newMatrix[newMatrixRow][i] = matrix[j][i];
            }
            newMatrixRow++;
        }
    }
    
    int i;
    for(i = 0; newMatrix[i][0] != null; i++);
    
    String finalMatrix[][] = new String[i][newMatrix[0].length];
    for (i = 0; i < finalMatrix.length; i++) {
        for (int j = 0; j < finalMatrix[i].length; j++)
            finalMatrix[i][j] = newMatrix[i][j];
    }
    
    return finalMatrix;
}
publicstaticvoidmain(字符串[]args){
System.out.println(“名称ID部门”);
//我添加了重复的行
字符串[][]输入阵列={
{“1”,“ram”,“Mech”},
{“1”,“湿婆”,“机械”},
{“1”,“gopi”,“Mech”},
{“1”,“gopi”,“Mech”},
{“4”,“jenkat”,“Mech”},
{“5”,“琳达”,“机械”},
{“1”,“velu”,“Mech”},
{“1”、“velu”、“Mech”}
};
//我将添加集合中的所有行,因为它不存储重复的值
Set solutionSet=new LinkedHashSet();
//我获取所有行,创建一个字符串并插入到集合中
for(int i=0;i
基于您的代码。也许这不是最好的解决方案,但它确实有效

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();
    }

}
public static String[][] removeDuplicate(String[][] matrix) {
    String[][] newMatrix = new String[matrix.length][matrix[0].length];
    int newMatrixRow = 1;

    for (int i = 0; i < matrix[0].length; i++)
        newMatrix[0][i] = matrix[0][i];

    for (int j = 1; j < matrix.length; j++) {
        List<Boolean> list = new ArrayList<>();
        for (int i = 0; newMatrix[i][0] != null; i++) {
            boolean same = true;
            for (int col = 2; col < matrix[j].length; col++) {
                if (!newMatrix[i][col].equals(matrix[j][col])) {
                    same = false;
                    break;
                }
            }
            list.add(same);
        }

        if (!list.contains(true)) {
            for (int i = 0; i < matrix[j].length; i++) {
                newMatrix[newMatrixRow][i] = matrix[j][i];
            }
            newMatrixRow++;
        }
    }
    
    int i;
    for(i = 0; newMatrix[i][0] != null; i++);
    
    String finalMatrix[][] = new String[i][newMatrix[0].length];
    for (i = 0; i < finalMatrix.length; i++) {
        for (int j = 0; j < finalMatrix[i].length; j++)
            finalMatrix[i][j] = newMatrix[i][j];
    }
    
    return finalMatrix;
}
publicstaticvoidmain(字符串[]args){
System.out.println(“名称ID部门”);
//我添加了重复的行
字符串[][]输入阵列={
{“1”,“ram”,“Mech”},
{“1”,“湿婆”,“机械”},
{“1”,“gopi”,“Mech”},
{“1”,“gopi”,“Mech”},
{“4”,“jenkat”,“Mech”},
{“5”,“琳达”,“机械”},
{“1”,“velu”,“Mech”},
{“1”、“velu”、“Mech”}
};
//我将添加集合中的所有行,因为它不存储重复的值
Set solutionSet=new LinkedHashSet();
//我获取所有行,创建一个字符串并插入到集合中
for(int i=0;i
我发布了一个我认为可读且易于维护的解决方案

我决定使用
distinct
from
Stream
,这是Java8的一部分

返回由此流的不同元素(根据Object.equals(Object))组成的流。-

Main.class

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);
    }
}
//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 + "]";
    }
}
Employee.class

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);
    }
}
//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 + "]";
    }
}

我已经发布了一个我认为可读且易于维护的解决方案

我决定使用
distinct
from
Stream
,这是Java8的一部分

返回由此流的不同元素(根据Object.equals(Object))组成的流。-

Main.class

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);
    }
}
//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 + "]";
    }
}
Employee.class

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);
    }
}
//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 + "]";
    }
}

Java-8之前的解决方案。可能不是最好的方法。但是一个快速有效的解决方案

String[][] records = {
            {"1","ram","Mech"},
            {"1","ram","Mech"},
            {"1","gopi","csc"},
            {"1","gopi","civil"} };

    List<String[]> distinctRecordsList = new ArrayList<String[]>();
    for(String[] record : records){
        if(distinctRecordsList.size()>0){
            boolean sameValue = false;
            for(String[] distinctRecord : distinctRecordsList){
                int distinctRecordFields = distinctRecord.length;
                if(record.length==distinctRecordFields){
                    for(int k=0;k<distinctRecordFields;k++){
                        sameValue = record[k].equalsIgnoreCase(distinctRecord[k]);
                        if(!sameValue)
                            break;
                    }
                }else
                    throw new Exception("Can't compare the records");
            }
            if(!sameValue)
                distinctRecordsList.add(record);
        }else if(distinctRecordsList.size()==0)
            distinctRecordsList.add(record);            
    }
    Object[] distRecObjects = distinctRecordsList.toArray();
    String[][] distinctRecordsArray = new String[distRecObjects.length][];

    int i=0;
    for(Object distRecObject : distRecObjects){
        distinctRecordsArray[i] = (String[]) distRecObject;
        i++;
    }
String[][