Home > Back-end >  Locating a specific part in a String array using a certain keyword Java
Locating a specific part in a String array using a certain keyword Java

Time:10-21

Im trying to create a method that will take in a String (name) and go through this array and keep only that specific line. I can not change how this info is stored as a lot of code is based on this arrangement.

Id like to put in "mike" and it remove all the other parts of the array and give me back that single line.

private static final String[][] MsgKeys =
            {
                    {"mike", "75", "up"},
                    {"john", "15", "up"},
                    {"eric", null, "left"},
                    {"mark", null, "right"},
                    {"chris", "87", "up"},
                    {"shawn", null, "left"},
                    {"blake", "67", "left"},
                    {"bentley", null, "right"}
        }

CodePudding user response:

I don't think removing anything is a good idea. Specifically, arrays have a fixed size, so you'd need to either change this to a list, or create a brand new array.

Since you didn't define the behavior of multiple rows with the same name, how about returning just the first matching row, or null if not found?

private String[] getRow(String name, String[][] data) {
  for (String[] row : data) {
    if (data[0].equals(name)) return row;
  }
  return null;
}

CodePudding user response:

You can not completly remove Elements out of an Array because it has a fixed length. What you can do is return a second 1d Array.

private String[] getLineByName(String name){
    String[] ret;
    for(int i = 0; i < MsgKeys.length; i  ){
        if(MsgKeys[i][0].equals(name)){
            ret = MsgKeys[i];
            return ret;
        }
    }
    return null;
}

CodePudding user response:

As mentioned in other answers you shouldn't remove elements from the array, but you can find the row using stream:

public static String[] findRow(String name, String[]... array) {
    return Arrays.stream(array)
            .filter(row -> Objects.equals(row[0], name))
            .findAny().orElse(null);
}

Then you can do:

String[] row = findRow("mike", MsgKeys);

System.out.println(Arrays.toString(row));

Output:

[mike, 75, up]
  • Related