Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I print the contents of a stream as numerated?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading