简体   繁体   中英

How to check if a value exists in an ArrayList that contains an ArrayList

So, I have an ArrayList that contains another ArrayList, and I'm trying to see if the inner Arraylist contains a value that I'm looking for. If it does, I want to return the index in which that array exists.

 List<List<String>> messages = parseMessages(extract.getPath());

        String needle = "test";
        messages.stream()  // Stream<List<String>>
                .filter(message -> message.contains(needle))
                .flatMap(List::stream)  // Stream<String>
                .forEach(System.out::println);

So I wrote this code after I captured an ArrayList within an ArrayList.

The array that I am trying to access is "Messages" which contains 2 other arraylist.

I want to use the contains method to check if the inner arraylist contains a value and return the index of that arrayList.

Thanks

Try this

messages.stream()  
        .filter(message -> message.contains(needle))
        .map(message -> message.indexOf(needle))
        .forEach(System.out::println);

The map stage returns the index of the value. This will continue for other lists even after matching inner list containing needle is found. To stop after the first match, you can use findFirst .

 messages.stream()
        .filter(message -> message.contains(needle))
        .map(message -> message.indexOf(needle))
        .findFirst()
        .ifPresent(System.out::println);

If you want to get the index of the outer list ,

IntStream.range(0, messages.size())
        .filter(index -> messages.get(index).contains(needle))
        .forEach(System.out::println);

Again, to stop after one match,

IntStream.range(0, messages.size())
        .filter(index -> messages.get(index).contains(needle))
        .findFirst()
        .ifPresent(System.out::println);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM