user2524908
user2524908

Reputation: 871

Java 8 find first instance of value in multidimensional array of objects

Trying to understand how to use some java 8 features and was playing around with multidimensional array of objects, if I wanted to find the first instance of a value in a multidimensional array of objects.

Objects[][] someArray= .....


Arrays.stream(someArray)
                .map(someArrayFirst -> Arrays.stream(someArrayFirst))
                .map(unsure what to do here)
                .filter(a -> a.equals("some value"))
                .findFirst();

edit, thanks for the input. Just to help others out here is what I have now.

 Arrays.stream(someArray)
                .flatMap(someArrayFirst -> Arrays.stream(someArrayFirst))
                .filter(MyCustomClass.class::isInstance)
                .map(MyCustomClass.class::cast)
                .filter(v -> v.value().equalsIgnoreCase("SomeString"))
                .findFirst();

Upvotes: 1

Views: 2418

Answers (2)

Petro Gordiyevich
Petro Gordiyevich

Reputation: 307

static String[][] arr = new String[][]{{"x","y"},{"z","v"},{"b","z"}};
static String searchStr = "x";
static String searchObj = null;

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

    Arrays.stream(arr)
    .forEach((subarr)->{
        Optional<String> opt = Arrays.stream(subarr)
                .filter((obj)->obj.equals(searchStr))
                .findFirst();
        if (opt.isPresent())
            searchObj = opt.get();
    });
    System.out.println(searchObj);
}

or

static public String mapFlatMethod(String[][] arr, String searchStr) {
    return Arrays.stream(arr).flatMap(row -> Stream.of(row))
            .filter((obj)->obj.equals(searchStr))
            .findFirst().get();

}

Upvotes: 1

sprinter
sprinter

Reputation: 27976

You are on the right track. You need to turn the two dimensions into a single stream and then take the first element that satisfies your condition:

String[][] array;
Optional<String> result = Arrays.stream(array)
    .flatMap(Arrays::stream)
    .filter("some value"::equals).findFirst();

The first stream produces a Stream<String[]>. The flat map turns each of the array elements into a Stream<String>. Then it's just filtering for the value you want and getting the first element that satisfies your condition.

Upvotes: 4

Related Questions