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

后端 未结 22 2787
天命终不由人
天命终不由人 2020-11-22 01:42

Is there a concise way to iterate over a stream whilst having access to the index in the stream?

String[] names = {\"Sam\",\"Pamela\", \"Dave\", \"Pascal\",          


        
22条回答
  •  天命终不由人
    2020-11-22 02:04

    With a List you can try

    List strings = new ArrayList<>(Arrays.asList("First", "Second", "Third", "Fourth", "Fifth")); // An example list of Strings
    strings.stream() // Turn the list into a Stream
        .collect(HashMap::new, (h, o) -> h.put(h.size(), o), (h, o) -> {}) // Create a map of the index to the object
            .forEach((i, o) -> { // Now we can use a BiConsumer forEach!
                System.out.println(String.format("%d => %s", i, o));
            });
    

    Output:

    0 => First
    1 => Second
    2 => Third
    3 => Fourth
    4 => Fifth
    

提交回复
热议问题