0

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

0

1 Answer 1

3

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); 
Sign up to request clarification or add additional context in comments.

5 Comments

Hmm, nothing gets printed out
Yeah I have that, i.e the bit from messages.stream() but nothing seems to get printed onto the console
What else you expect to be printed? Can you show the code/example?
Ok nevermind, so I am able to print the contents of my ArrayList, however, I was only able to do that when I removed the code for checking if the list contains the value stored in the needle. I can defintley see element that I'm looking for in teh inner array, but programatically it cant find it
I don't get you. See the updated code on Ideone. I have added code for printing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.