Comparing two rows in a single 2D array

2019-08-03 10:23发布

I am trying to compare two rows that are in different order from a 2D array, and store elements that are the same from both rows. Here's an example of what I have produced:

String[] row1 = new String[10];
String[] row2 = new String[10];
String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};

for (int i = 0; i < fruit.length; i++ ) {
    for (int j = 0; j < fruit[i].length; j++){
            if(fruit[0][j].equals(fruit[1][j])) {
                row1[j] = fruit[0][j];
                row2[j] = fruit[1][j];

                System.out.println("Match found");
            }else{
                System.out.println("Not found"); 
            }
    }   
}
System.out.println("row1");
System.out.println(Arrays.deepToString(row1));
System.out.println("row2");
System.out.println(Arrays.deepToString(row2));

I want the row1[] and row2[] to store the elements that are the same (which is kiwi in this example). However, the problem is .equals function only detects matching patterns. The example above only prints out nulls from row1 and row2.

It should really print out:

row1
[kiwi]
row2
[kiwi]

Note: I don't want to declare... String check = "kiwi"; because the user can enter anything in the 2D array.

Any suggestions? I feel I am getting close. I saw a similar example of someone using .equals and that worked, but it was only for single arrays.

4条回答
做个烂人
2楼-- · 2019-08-03 10:37

It is less confusing to put the sub-arrays into temporary (1D) arrays: row1Temp and row2Temp.

   import  java.util.Arrays;
/**
   <P>{@code java DoubleArrayXmpl}</P>
 **/
public class DoubleArrayXmpl  {
   public static final void main(String[] igno_red)  {
      String[] row1Output = new String[10];
      String[] row2Output = new String[10];

      String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};

      String[] row1Temp = fruit[0];
      String[] row2Temp = fruit[1];

      for(int i = 0; i < row1Temp.length; i++)  {
         for(int j = 0; j < row2Temp.length; j++)  {
            if(row1Temp[i].equals(row2Temp[j])) {
                System.out.println("Match found");
               row1Output[i] = row1Temp[i];
               row2Output[j] = row2Temp[j];
            }else{
                System.out.println("Not found");
            }
         }
      }

      System.out.println("row1Output");
      System.out.println(Arrays.deepToString(row1Output));
      System.out.println("row2Output");
      System.out.println(Arrays.deepToString(row2Output));
   }
}

Output:

[C:\java_code\]java DoubleArrayXmpl
Not found
Not found
Not found
Not found
Not found
Not found
Match found
Not found
Not found
row1Output
[null, null, kiwi, null, null, null, null, null, null, null]
row2Output
[kiwi, null, null, null, null, null, null, null, null, null]

I don't know your requirements, but It's a little odd to put these duplicate values into two different arrays, let alone leaving so many values null. How about using an ArrayList to store a single copy of the matched fruit?

   import  java.util.Arrays;
/**
   <P>{@code java DoubleArrayXmpl}</P>
 **/
public class DoubleArrayXmpl  {
   public static final void main(String[] igno_red)  {
      ArrayList<String> alMatches = new ArrayList<String>(3);

      String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};

      String[] row1Temp = fruit[0];
      String[] row2Temp = fruit[1];

      for(int i = 0; i < row1Temp.length; i++)  {
         for(int j = 0; j < row2Temp.length; j++)  {
            if(row1Temp[i].equals(row2Temp[j])) {
                System.out.println("Match found");
                alMatches.add(row1Temp[i]);
            }else{
                System.out.println("Not found");
            }
         }
      }

      System.out.println("All matched fruits:");
      for(String s : alMatches)  {
         System.out.println(s);
      }
   }
}

Output:

Not found
Not found
Not found
Not found
Not found
Not found
Match found
Not found
Not found
All matched fruits:
kiwi

Or even better, just store the indexes of the matches:

   import  java.util.Arrays;
     import  java.util.ArrayList;
/**
   <P>{@code java DoubleArrayToMatchedIdxListXmpl}</P>
 **/
public class DoubleArrayToMatchedIdxListXmpl  {
   public static final void main(String[] igno_red)  {
      ArrayList<Integer> alMatchIdxsInRow1 = new ArrayList<Integer>(3);

      String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};

      String[] row1Temp = fruit[0];
      String[] row2Temp = fruit[1];

      for(int i = 0; i < row1Temp.length; i++)  {
         for(int j = 0; j < row2Temp.length; j++)  {
            if(row1Temp[i].equals(row2Temp[j])) {
                System.out.println("Match found");
                alMatchIdxsInRow1.add(i);
            }else{
                System.out.println("Not found");
            }
         }
      }

      System.out.println("All matched fruits:");
      for(int i : alMatchIdxsInRow1)  {
         System.out.println(fruit[0][i]);
      }
   }
}

Output:

Not found
Not found
Not found
Not found
Not found
Not found
Match found
Not found
Not found
All matched fruits:
kiwi
查看更多
Bombasti
3楼-- · 2019-08-03 10:41

The limits of your for-loops have been messed up, as well as the array elements that you accessed for comparison. I guess you wanted something like this...

import java.util.Arrays;

public class RowCompare
{
    public static void main(String[] args)
    {
        String[] row1 = new String[10];
        String[] row2 = new String[10];
        String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};

        for (int i = 0; i < fruit[0].length; i++ ) {
            for (int j = 0; j < fruit[1].length; j++){
                    if(fruit[0][i].equals(fruit[1][j])) {
                        row1[i] = fruit[0][i];
                        row2[j] = fruit[1][j];

                        System.out.println("Match found");
                    }else{
                        System.out.println("Not found");
                    }
            }
        }
        System.out.println("row1");
        System.out.println(Arrays.deepToString(row1));
        System.out.println("row2");
        System.out.println(Arrays.deepToString(row2));
    }
}

But you should probably describe what you want to do with the results. These fixed-size result arrays (String[10]) look dubious, and the currently sketched code can not easily be generalized for MORE than 2 rows. There is probably a MUCH more elegant solution using Sets and Lists ....

查看更多
【Aperson】
4楼-- · 2019-08-03 10:52

You're logic is slightly wrong in your loop.

If you look you are comparing

 fruit[0][0].equals(fruit[1][0])

then

 fruit[0][1].equals(fruit[1][1])

change if statement to

if(fruit[0][i].equals(fruit[1][j])) {
查看更多
欢心
5楼-- · 2019-08-03 10:59

Your solution is very uneffective since you don't take advantage of the optimization algorythms like hashing:

You should use a HashSet or a HashMap to find fastly if an element is contained.

In addition collections have ready methods like retainAll() to keep only the existing elements (HashSet implements Collection so it's a good candidate for your needs)

retainAll: Retains only the elements in this collection that are contained in the specified collection (optional operation)

HashSet row1 = new HashSet();
row1.add("Kiwi");
...
HashSet row2 = new HashSet();
row2.add...

System.out.println( row1.retainAll(row2) );
查看更多
登录 后发表回答