-1

I'm iterating over an ArrayList with String arrays inside.

["A","1"]
["A","2"]
["A","3"]
["B","1"]
["B","2"]
["B","3"]

How can I select only the ones with an "A" on the first position? Without iterating, and saving on a new array...

for (String[] key : keys){  
}

Using a for each for example, what I want is, for the first iteration -> only work with the String Arrays with "A", second iteration -> only work with the String Arrays with "B".

Rayden
  • 160
  • 1
  • 9

3 Answers3

2

Try this:

    String[][] keys = {
        {"A","1"},
        {"A","2"},
        {"A","3"},
        {"B","1"},
        {"B","2"},
        {"B","3"},
    };
    String[][] result = Stream.of(keys)
        .filter(x -> x[0].equals("A"))
        .toArray(String[][]::new);
    System.out.println(Arrays.deepToString(result));
0

Are you looking for a solution with Java 8?

List<String[]> result = keys.stream()
                            .filter(t -> "A".equals(t[0]))
                            .collect(Collectors.toList());
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
-1

you can´t without going through each one (either iterating or in parallel). But you probably want a Map. Check this : http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

jambriz
  • 1,273
  • 1
  • 10
  • 25