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
1 Answer 1
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);
-
Hmm, nothing gets printed outMatt– Matt2018年05月23日 14:58:12 +00:00Commented 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 consoleMatt– Matt2018年05月23日 15:05:50 +00:00Commented May 23, 2018 at 15:05
-
What else you expect to be printed? Can you show the code/example?Thiyagu– Thiyagu2018年05月23日 15:08:15 +00:00Commented 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 itMatt– Matt2018年05月23日 15:09:46 +00:00Commented May 23, 2018 at 15:09
-
I don't get you. See the updated code on Ideone. I have added code for printing.Thiyagu– Thiyagu2018年05月23日 15:14:45 +00:00Commented May 23, 2018 at 15:14