How to add/append new rows from Array1[][] that do not exist in Array2[][] to Array2[][] in Java?

huangapple go评论56阅读模式
英文:

How to add/append new rows from Array1[][] that do not exist in Array2[][] to Array2[][] in Java?

问题

我遇到了一个问题,需要检查Array1中不在Array2中的行,并将其附加到Array2的末尾(Java中)。关于第一列(即姓名)的公共行可以跳过。在下面的示例中,应该将在firstarray中的“Nick”和“Bruce”行附加到secondarray的末尾。

我已经稍微编辑了数组以获得更清楚的理解。

String firstarray[][] = {
    {"John","04-Feb-1982","Economics","Leeds"},
    {"Mathias","08-Jan-1985","Arts","London"},
    {"Nick","09-06-1974","History","Johanesburg"},
    {"Bruce","13-08-1975","Philosophy","Seattle"}};
       
String secondarray[][] = {
    {"Adam","01-Dec-1980","Commerce","New York"},
    {"John","04-Feb-1982","Economics","Leeds"},
    {"Mathias","08-Jan-1985","Arts","London"}};

解决方案应如下所示:

secondarray[][]:
    {"Adam","01-Dec-1980","Commerce","New York"},
    {"John","04-Feb-1982","Economics","Leeds"},
    {"Mathias","08-Jan-1985","Arts","London"},
    {"Nick","09-06-1974","History","Johanesburg"},
    {"Bruce","13-08-1975","Philosophy","Seattle"}}
英文:

I came across a problem where one needs to check for rows in Array1 that are not in Array2 and append it at the end of Array2 in Java. The rows that are common with regard to the first column i.e. name can be skipped. In the below example, the rows in firstarray with "Nick" and "Bruce" should be appended at the end of secondarray.

I have edited the arrays again slightly to get more clarity.

String firstarray[][] = {
	{"John","04-Feb-1982","Economics","Leeds"},
	{"Mathias","08-Jan-1985","Arts","London"},
	{"Nick","09-06-1974","History","Johanesburg"},
	{"Bruce","13-08-1975","Philosophy","Seattle"}};
	       
String secondarray[][] = {
	{"Adam","01-Dec-1980","Commerce","New York"},
	{"John","04-Feb-1982","Economics","Leeds"},
	{"Mathias","08-Jan-1985","Arts","London"}};

The solution should be like:

secondarray[][]:
    {"Adam","01-Dec-1980","Commerce","New York"},
    {"John","04-Feb-1982","Economics","Leeds"},
    {"Mathias","08-Jan-1985","Arts","London"},
    {"Nick","09-06-1974","History","Johanesburg"},
    {"Bruce","13-08-1975","Philosophy","Seattle"}}

答案1

得分: 1

收集第二个数组的名称到一个集合中,遍历第一个数组并过滤出那些在集合中的元素,并将结果收集到第三个数组(或任何其他集合)中。将这个集合追加到第二个数组。

public static void main(String[] args){
    String firstarray[][] = {
        {"Adam","01-Dec-1980","Commerce","Kansas"},
        {"John","04-Feb-1982","Economics","Leeds"},
        {"Mathias","08-Jan-1985","Arts","London"},
        {"Nick","09-06-1974","History","Johanesburg"},
        {"Bruce","13-08-1975","Philosophy","Seattle"}};

    String secondarray[][] = {
        {"Adam","01-Dec-1980","Commerce","Kansas"},
        {"John","04-Feb-1982","Economics","Leeds"},
        {"Mathias","08-Jan-1985","Arts","London"},
        {"Sujay Muramalla","08-Jan-1985","Arts","London"}};

    //将第二个数组的名称收集到集合中
    Set<String> secondSet = Arrays.stream(secondarray).map(e -> e[0]).collect(Collectors.toSet());
    //在第一个数组上进行流操作,仅保留不在上述集合中的元素
    String[][] third = Arrays.stream(firstarray)
            .filter(e -> !secondSet.contains(e[0]))
            .toArray(String[][]::new);
    //在第二个和第三个数组上进行流操作,并收集到一个结果数组中
    String[][] result = Stream.concat(Arrays.stream(secondarray), Arrays.stream(third))
            .toArray(String[][]::new);
    
    //输出
    Arrays.stream(result).forEach(e ->{
        System.out.println(Arrays.toString(e));
    });
}

(注意:此处为代码翻译,代码的逻辑和功能保持不变。)

英文:

Collect the names of the second array to a set, iterate over your first array and filter out those elements which are in the set and collect the result in a third array (or any other collection). Append this collection to your second array.

public static void main(String[] args){
String firstarray[][] = {
{&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
{&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
{&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;},
{&quot;Nick&quot;,&quot;09-06-1974&quot;,&quot;History&quot;,&quot;Johanesburg&quot;},
{&quot;Bruce&quot;,&quot;13-08-1975&quot;,&quot;Philosophy&quot;,&quot;Seattle&quot;}};
String secondarray[][] = {
{&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
{&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
{&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;},
{&quot;Sujay Muramalla&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;}};
//collect names of second array to set
Set&lt;String&gt; secondSet = Arrays.stream(secondarray).map(e -&gt; e[0]).collect(Collectors.toSet());
//stream over your first array and keep only those which are not in the above set
String[][] third = Arrays.stream(firstarray)
.filter(e -&gt; !secondSet.contains(e[0]))
.toArray(String[][]::new);
//stream over second and delta (third array) and collect to a result array
String[][] result = Stream.concat(Arrays.stream(secondarray), Arrays.stream(third))
.toArray(String[][]::new);
//output
Arrays.stream(result).forEach(e -&gt;{
System.out.println(Arrays.toString(e));
});
}

答案2

得分: 0

EDIT 1 - 使用自定义类
我建议您始终使用 List 而不是 Array

import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

    static class Person {
        public String name;
        public String birthDate;
        public String field;
        public String city;

        public static Person fromArray(String[] data) {
            Person p = new Person();
            if (data.length == 4) {
                p.name = data[0];
                p.birthDate = data[1];
                p.field = data[2];
                p.city = data[3];
            } else {
                // 处理方法
            }
            return p;
        }

        @Override
        public String toString() {
            return new StringBuilder("[")
                    .append(name)
                    .append(",").append(birthDate)
                    .append("] learns ").append(field)
                    .append(" at ").append(city)
                    .toString();
        }
    }

    public static void main(String[] args) {
        String firstArray[][] = {
                {"Adam","01-Dec-1980","Commerce","Kansas"},
                {"John","04-Feb-1982","Economics","Leeds"},
                {"Mathias","08-Jan-1985","Arts","London"},
                {"Nick","09-06-1974","History","Johanesburg"},
                {"Bruce","13-08-1975","Philosophy","Seattle"}
        };

        String secondArray[][] = {
                {"Adam","01-Dec-1980","Commerce","Kansas"},
                {"John","04-Feb-1982","Economics","Leeds"},
                {"Mathias","08-Jan-1985","Arts","London"}
        };

        List<Person> finalList = getFinalList(firstArray, secondArray);
        // 显示
        System.out.println(finalList);
    }

    public static List<Person> getFinalList(String[][] arr1, String[][] arr2) {
        // 首先将数组转换为 Person 列表
        List<Person> firstList = Arrays.stream(arr1).map(Person::fromArray).collect(Collectors.toList());
        List<Person> secondList = Arrays.stream(arr2).map(Person::fromArray).collect(Collectors.toList());

        // 获取第二个列表中的姓名
        Set<String> existingNames = secondList.stream().map(p -> p.name).collect(Collectors.toSet());
        System.out.println("Names: " + existingNames);

        firstList.forEach(person -> {
            if (!existingNames.contains(person.name)) {
                secondList.add(person);
            }
        });
        return secondList;
    }
}
英文:

EDIT 1 - Using Custom Class
I suggest you to always use List over Array.

import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

    static class Person {
        public String name;
        public String birthDate;
        public String field;
        public String city;

        public static Person fromArray(String[] data) {
            Person p = new Person();
            if (data.length == 4) {
                p.name = data[0];
                p.birthDate = data[1];
                p.field = data[2];
                p.city = data[3];
            } else {
                // Handle me
            }
            return p;
        }

        @Override
        public String toString() {
            return new StringBuilder(&quot;[&quot;).append(name)
                    .append(&quot;,&quot;).append(birthDate)
                    .append(&quot;] learns &quot;).append(field)
                    .append(&quot; at &quot;).append(city).toString();
        }
    }

    public static void main(String[] args) {
        String firstArray[][] = {
                {&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
                {&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
                {&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;},
                {&quot;Nick&quot;,&quot;09-06-1974&quot;,&quot;History&quot;,&quot;Johanesburg&quot;},
                {&quot;Bruce&quot;,&quot;13-08-1975&quot;,&quot;Philosophy&quot;,&quot;Seattle&quot;}};

        String secondArray[][] = {
                {&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
                {&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
                {&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;}};

        List&lt;Person&gt; finalList = getFinalList(firstArray, secondArray);
        // Display
        System.out.println(finalList);
    }

    public static List&lt;Person&gt; getFinalList(String[][] arr1, String[][] arr2) {
        // First cast to Lists of persons
        List&lt;Person&gt; firstList = Arrays.asList(arr1).stream().map(Person::fromArray).collect(Collectors.toList());
        List&lt;Person&gt; secondList = Arrays.asList(arr2).stream().map(Person::fromArray).collect(Collectors.toList());

        // Get names in secondList
        Set&lt;String&gt; existingNames = secondList.stream().map(p -&gt; p.name).collect(Collectors.toSet());
        System.out.println(&quot;Names: &quot;+ existingNames);

        firstList.forEach(person -&gt; {
            if (! existingNames.contains(person.name)) {
                secondList.add(person);
            }
        });
        return secondList;
    }
}

答案3

得分: 0

你不应该使用数组来处理这个问题。最好使用已经完成这项工作的库。

即使你接收到的数据已经是那样,你可以首先将其转换为 Map<String, Person>,这样代码会更高效和易读。

使用数组或者许多不使用一些哈希系统的解决方案,会导致指数级复杂度 O(n^2),因此效率不高。

至少要转换 secondarray

Map<String, Person> secondMap = new HashMap<>();
for(String[] row : secondarray){
    secondMap.put(row[0], new Person(row[0], row[1], row[2], row[3]));
}

然后,如果尚未存在于映射中,将其放入映射中:

for(String[] row : firstarray){
    if(!secondMap.containsKey(row[0])){
        secondMap.put(row[0], new Person(row[0], row[1], row[2], row[3]));
    }
}

其中,Person 类可以简单地定义为:

private static class Person{
    
    public Person(String name, String birth, String area, String city){
        this.name = name;
        this.birth = birth;
        this.area = area;
        this.city = city;
    }
    
    String name;
    String birth;
    String area;
    String city;
}
英文:

You should not be using arrays for this. Much better to use libraries already doing the job.

Even if the data you receive is already that way, you can converted first to a Map<String, Person> it will be more efficient, and readable code.

With arrays or many solutions not using some hashing system, you end up with exponential complexity O(n2), so not efficient.

Convert at least secondarray

Map&lt;String, Person&gt; secondMap = new HashMap();
for(String [] row : secondarray){
secondMap.put(row[0], new Person(row[0], row[1], row[2], row[3]));
}

Then put in the map if not already there

for(String[] row : firstarray){
if(!secondMap.containsKey(row[0])){
secondMap.put(row[0], new Person(row[0], row[1], row[2], row[3]));
}
}

Where Person class could be simply defined as

private static class Person{
public Person(String name, String birth, String area, String city){
this.name = name;
this.birth = birth;
this.area = area;
this.city = city;
}
String name;
String birth;
String area;
String city;
}

答案4

得分: 0

如果您想检查数组的多于第一个元素的部分您可以使用nopens的解决方案并将`e[0]`替换为`Arrays.toString(e)`。

如果可能的话一种更简洁的方法是使用一个带有对象的列表并使用一个id来检查equals或者重写客户对象的hashcode函数您还可以像这样检查名称和生日

```java
class Customer {
    private String name;
    private String birth;
    private String type;
    private String location;

    public Customer(String name, String birth, String type, String location) {
        this.name = name;
        this.birth = birth;
        this.type = type;
        this.location = location;
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", birth=" + birth + ", type=" + type + ", location=" + location + "]";
    }
}

List<Customer> firstList = new ArrayList<Customer>();
firstList.add(new Customer("Adam", "01-Dec-1980", "Commerce", "Kansas"));
firstList.add(new Customer("John", "04-Feb-1982", "Economics", "Leeds"));
firstList.add(new Customer("Mathias", "08-Jan-1985", "Arts", "London"));
firstList.add(new Customer("Nick", "09-06-1974", "History", "Johanesburg"));
firstList.add(new Customer("Bruce", "13-08-1975", "Philosophy", "Seattle"));

List<Customer> secondList = new ArrayList<Customer>();
secondList.add(new Customer("Adam", "01-Dec-1980", "Commerce", "Kansas"));
secondList.add(new Customer("John", "04-Feb-1982", "Economics", "Leeds"));
secondList.add(new Customer("Mathias", "08-Jan-1985", "Arts", "London"));

for (Customer customer : firstList) {
    if (containsNameAndBirth(secondList, customer) == false) {
        secondList.add(customer);
    }
}

for (Customer customer : secondList) {
    System.out.println(customer);
}

}

public static boolean containsNameAndBirth(final List<Customer> list, final Customer customer) {
    return list.stream().filter(o -> o.name.equals(customer.name) && o.birth.equals(customer.birth)).findFirst()
            .isPresent();
}
英文:

if you want check more than the first element of the array you can use nopens solution and replace e[0] with Arrays.toString(e).

A cleaner way if this is possible for you, is to use a list with a object and use a id for checking equals or override the hashcode function of the customer object.
You can also check for name and birth like that:

class Customer {
private String name;
private String birth;
private String type;
private String location;
public Customer(String name, String birth, String type, String location) {
this.name = name;
this.birth = birth;
this.type = type;
this.location = location;
}
@Override
public String toString() {
return &quot;Customer [name=&quot; + name + &quot;, birth=&quot; + birth + &quot;, type=&quot; + type + &quot;, location=&quot; + location + &quot;]&quot;;
}
}
List&lt;Customer&gt; firstList = new ArrayList&lt;Customer&gt;();
firstList.add(new Customer(&quot;Adam&quot;, &quot;01-Dec-1980&quot;, &quot;Commerce&quot;, &quot;Kansas&quot;));
firstList.add(new Customer(&quot;John&quot;, &quot;04-Feb-1982&quot;, &quot;Economics&quot;, &quot;Leeds&quot;));
firstList.add(new Customer(&quot;Mathias&quot;, &quot;08-Jan-1985&quot;, &quot;Arts&quot;, &quot;London&quot;));
firstList.add(new Customer(&quot;Nick&quot;, &quot;09-06-1974&quot;, &quot;History&quot;, &quot;Johanesburg&quot;));
firstList.add(new Customer(&quot;Bruce&quot;, &quot;13-08-1975&quot;, &quot;Philosophy&quot;, &quot;Seattle&quot;));
List&lt;Customer&gt; secondList = new ArrayList&lt;Customer&gt;();
secondList.add(new Customer(&quot;Adam&quot;, &quot;01-Dec-1980&quot;, &quot;Commerce&quot;, &quot;Kansas&quot;));
secondList.add(new Customer(&quot;John&quot;, &quot;04-Feb-1982&quot;, &quot;Economics&quot;, &quot;Leeds&quot;));
secondList.add(new Customer(&quot;Mathias&quot;, &quot;08-Jan-1985&quot;, &quot;Arts&quot;, &quot;London&quot;));
for (Customer customer : firstList) {
if (containsNameAndBirth(secondList, customer) == false) {
secondList.add(customer);
}
}
for (Customer customer : secondList) {
System.out.println(customer);
}
}
public static boolean containsNameAndBirth(final List&lt;Customer&gt; list, final Customer customer) {
return list.stream().filter(o -&gt; o.name.equals(customer.name) &amp;&amp; o.birth.equals(customer.birth)).findFirst()
.isPresent();
}

答案5

得分: 0

我点赞了nopens的解决方案,因为它很不错。
这里有另一个解决方案,它使用了映射并利用了一种跳过常见键的逻辑,通过在映射的键集上使用removeAll方法,这是一种在Java变得更具“功能性”之前就存在的功能性方法。

static public <T> Map<T,T[]> arrayToMap(T[][] array, int i) {
return Arrays.stream(array).collect(Collectors.toMap(e -> e[i], e -> e));
}
public static void main(String[] args){
String firstarray[][] = {
{"Adam","01-Dec-1980","Commerce","Kansas"},
{"John","04-Feb-1982","Economics","Leeds"},
{"Mathias","08-Jan-1985","Arts","London"},
{"Nick","09-06-1974","History","Johanesburg"},
{"Bruce","13-08-1975","Philosophy","Seattle"}};
String secondarray[][] = {
{"Adam","01-Dec-1980","Commerce","Kansas"},
{"John","04-Feb-1982","Economics","Leeds"},
{"Mathias","08-Jan-1985","Arts","London"},
{"Sujay Muramalla","08-Jan-1985","Arts","London"}};
Map<String,String[]> firstMap = arrayToMap(firstarray, 0);
Map<String,String[]> secondMap = arrayToMap(secondarray, 0);
secondMap.keySet().removeAll(firstMap.keySet());
firstMap.putAll(secondMap);	    
String[][] result = firstMap.values().stream().toArray(String[][]::new);
//output
Arrays.stream(result).forEach(e ->{
System.out.println(Arrays.toString(e));
});
}

附注:在arrayToMap中,您可以选择使用哪一列作为键。
而且逻辑甚至可以简化为以下3行代码:

    Map<String,String[]> firstMap = arrayToMap(firstarray, 0);
firstMap.putAll(arrayToMap(secondarray, 0));	
String[][] result = firstMap.values().stream().toArray(String[][]::new);

因为使用相同的键插入值会覆盖现有值,并且在键相等的情况下,如果值相同,则会得到相同的值。

英文:

I upvoted nopens solutions cause it is nice one
Here another that uses maps and makes use of a logic of skipping common keys using removeAll on the keySet of the map, which was a functional method existing befor Java turned "more" functional

static public &lt;T&gt; Map&lt;T,T[]&gt; arrayToMap(T[][] array, int i) {
return Arrays.stream(array).collect(Collectors.toMap(e -&gt; e[i], e -&gt; e));
}
public static void main(String[] args){
String firstarray[][] = {
{&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
{&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
{&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;},
{&quot;Nick&quot;,&quot;09-06-1974&quot;,&quot;History&quot;,&quot;Johanesburg&quot;},
{&quot;Bruce&quot;,&quot;13-08-1975&quot;,&quot;Philosophy&quot;,&quot;Seattle&quot;}};
String secondarray[][] = {
{&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
{&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
{&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;},
{&quot;Sujay Muramalla&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;}};
Map&lt;String,String[]&gt; firstMap = arrayToMap(firstarray, 0);
Map&lt;String,String[]&gt; secondMap = arrayToMap(secondarray, 0);
secondMap.keySet().removeAll(firstMap.keySet());
firstMap.putAll(secondMap);	    
String[][] result = firstMap.values().stream().toArray(String[][]::new);
//output
Arrays.stream(result).forEach(e -&gt;{
System.out.println(Arrays.toString(e));
});
}

sidenote: in arrayToMap you can choose which column you use as key.

And the logic could be even reduced to this 3 lines:

    Map&lt;String,String[]&gt; firstMap = arrayToMap(firstarray, 0);
firstMap.putAll(arrayToMap(secondarray, 0));	
String[][] result = firstMap.values().stream().toArray(String[][]::new);

since inserting a value with the same key overwrites the existing one and you get the same if the values are the same in case of equal keys.

答案6

得分: 0

一个简单且高效的方法(如果您不关心顺序)如下:

时间复杂度:O(nlog(n))
空间复杂度:O(n+m)

import java.util.Arrays;

public class Main {

    public static void main(String ... args) {

        String firstarray[][] = {
                {"John","04-Feb-1982","Economics","Leeds"},
                {"Mathias","08-Jan-1985","Arts","London"},
                {"Nick","09-06-1974","History","Johanesburg"},
                {"Bruce","13-08-1975","Philosophy","Seattle"}};

        String secondarray[][] = {
                {"Adam","01-Dec-1980","Commerce","Kansas"},
                {"John","04-Feb-1982","Economics","Leeds"},
                {"Mathias","08-Jan-1985","Arts","London"}};

        String result [][] =  new String[firstarray.length
                + secondarray.length][firstarray[0].length];

        // 对 firstarray 进行排序
        Arrays.sort(firstarray, (a, b) -> a[0].compareTo(b[0]));

        // 对 secondarray 进行排序
        Arrays.sort(secondarray, (a, b) -> a[0].compareTo(b[0]));

        int i = 0, j=0, k=0, cmp ;
        for ( ;i < secondarray.length && j< firstarray.length;) {

            cmp = firstarray[i][0].compareTo(secondarray[j][0]);
            if(cmp ==0) {
                System.arraycopy(firstarray[i], 0, result[k++], 0, 4);
                i++; j++;
            }else if( cmp < 0){
                System.arraycopy(firstarray[i], 0, result[k++], 0, 4);
                i++;
            } else {
                System.arraycopy(secondarray[j], 0, result[k++], 0, 4);
                j++;
            }
        }

        // 将 firstarray 中剩余的部分复制到 result
        for (; i < firstarray.length; i++) {
            System.arraycopy(firstarray[i], 0, result[k++], 0, 4);
        }

        // 将 secondarray 中剩余的部分复制到 result
        for (; j < secondarray.length; j++) {
            System.arraycopy(secondarray[j], 0, result[k++], 0, 4);
        }
        
        // 调整大小
        secondarray = Arrays.copyOf(result, k);

        // 只打印 secondarray
        for (int x = 0; x < secondarray.length; x++) {

           for (int y = 0; y < 4; y++) {
               System.out.print(secondarray[x][y] + ",");
            }
            System.out.println("");
        }

    }
}
英文:

A simple an efficient way to do it (if you don't care about ordering) is the following:

Time complexity: O(nlog(n))

Space complexity: O(n+m)

import java.util.Arrays;

public class Main {

    public static void main(String ... args) {

        String firstarray[][] = {
                {&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
                {&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;},
                {&quot;Nick&quot;,&quot;09-06-1974&quot;,&quot;History&quot;,&quot;Johanesburg&quot;},
                {&quot;Bruce&quot;,&quot;13-08-1975&quot;,&quot;Philosophy&quot;,&quot;Seattle&quot;}};

        String secondarray[][] = {
                {&quot;Adam&quot;,&quot;01-Dec-1980&quot;,&quot;Commerce&quot;,&quot;Kansas&quot;},
                {&quot;John&quot;,&quot;04-Feb-1982&quot;,&quot;Economics&quot;,&quot;Leeds&quot;},
                {&quot;Mathias&quot;,&quot;08-Jan-1985&quot;,&quot;Arts&quot;,&quot;London&quot;}};

        String result [][] =  new String[firstarray.length
                + secondarray.length][firstarray[0].length];

        // sort firstarray
        java.util.Arrays.sort(firstarray, new java.util.Comparator&lt;String[]&gt;() {
            public int compare(String [] a, String[] b) {
                return a[0].compareTo(b[0]);
            }
        });

        //sort secondarray
        java.util.Arrays.sort(secondarray, new java.util.Comparator&lt;String[]&gt;() {
            public int compare(String [] a, String[] b) {
                return a[0].compareTo(b[0]);
            }
        });
 

        int i = 0, j=0, k=0, cmp ;
        for ( ;i &lt; secondarray.length &amp;&amp; j&lt; firstarray.length;) {

            cmp = firstarray[i][0].compareTo(secondarray[j][0]);
            if(cmp ==0) {
                System.arraycopy(firstarray[i], 0, result[k++], 0, 4);
                i++; j++;
            }else if( cmp &lt;0){
                System.arraycopy(firstarray[i], 0, result[k++], 0, 4);
                i++;
            } else {
                System.arraycopy(secondarray[j], 0, result[k++], 0, 4);
                j++;
            }
        }

        // copy the remaining if any from firstarray to the result
        for (; i &lt; firstarray.length; i++) {
            System.arraycopy(firstarray[i], 0, result[k++], 0, 4);
        }

        // copy the remaining if any from secondarray to the result
        for (; j &lt; secondarray.length; j++) {
            System.arraycopy(secondarray[j], 0, result[k++], 0, 4);
        }
        
        //resize it
        secondarray = Arrays.copyOf(result, k);

        // just print the secondarray
        for (int x = 0; x &lt; secondarray.length; x++) {

           for (int y = 0; y &lt; 4; y++) {
               System.out.print(secondarray[x][y] + &quot;,&quot;);
            }
            System.out.println(&quot;&quot;);
        }

    }
}

huangapple
  • 本文由 发表于 2020年9月25日 15:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64059730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定