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

asked May 23, 2018 at 14:45
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);
answered May 23, 2018 at 14:49
5
  • Hmm, nothing gets printed out Commented May 23, 2018 at 14:58
  • Yeah I have that, i.e the bit from messages.stream() but nothing seems to get printed onto the console Commented May 23, 2018 at 15:05
  • What else you expect to be printed? Can you show the code/example? Commented May 23, 2018 at 15:08
  • 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 Commented May 23, 2018 at 15:09
  • I don't get you. See the updated code on Ideone. I have added code for printing. Commented May 23, 2018 at 15:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.