Suppose words is a reference variable that refers to an object of ArrayList<String>. The object contains some words (e.g. "book", "pencil", "notebook")
Is there a way to display contents of the collection as the following, using stream?
1 book
2 pencil
3 notebook
By the way, I can do the task without a stream:
for (int k = 0; k < words.size(); k++) {
System.out.println("" + (k + 1) + '\t' + words.get(k));
My try:
int k = 1;
words.forEach( word-> System.out.println("" + k++ + "\t" + word));
But it’s wrong:
java: local variables referenced from a lambda expression must be final or effectively final
>Solution :
You can do it like this. Just use IntStream to generate the indices of the list.
List<String> list = List.of("A","B","C");
IntStream.range(0,list.size())
.mapToObj(i-> (i + 1)+": " +list.get(i)).forEach(System.out::println);
prints
1: A
2: B
3: C
You can also do it your initial way by using AtomicInteger to avoid the effective final limitation.
AtomicInteger count = new AtomicInteger(1);
list.forEach(word ->
System.out.printf("%d: %s%n", count.getAndIncrement(), word));