Is there a concise way to iterate over a stream with indices in Java 8?

The cleanest way is to start from a stream of indices: String[] names = {“Sam”, “Pamela”, “Dave”, “Pascal”, “Erik”}; IntStream.range(0, names.length) .filter(i -> names[i].length() <= i) .mapToObj(i -> names[i]) .collect(Collectors.toList()); The resulting list contains “Erik” only. One alternative which looks more familiar when you are used to for loops would be to maintain an ad … Read more

Limit a stream by a predicate

Operations takeWhile and dropWhile have been added to JDK 9. Your example code IntStream .iterate(1, n -> n + 1) .takeWhile(n -> n < 10) .forEach(System.out::println); will behave exactly as you expect it to when compiled and run under JDK 9. JDK 9 has been released. It is available for download here: JDK 9 Releases.

Compare two lists of strings using java stream

First of all, the existing solution with a loop is just fine. Simply translating it to a solution that uses streams is not an improvement. Here’s how I would do it. NB: this is not tested. // Naive version List<String> nameList1 = Arrays.asList(“Bill”, “Steve”, “Mark”); List<String> nameList2 = Arrays.asList(“Steve Jobs”, “Mark”, “Bill”); List<String> matchList = … Read more