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

后端 未结 22 2315
天命终不由人
天命终不由人 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:11

    You can use IntStream.iterate() to get the index:

    String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
    List nameList = IntStream.iterate(0, i -> i < names.length, i -> i + 1)
            .filter(i -> names[i].length() <= i)
            .mapToObj(i -> names[i])
            .collect(Collectors.toList());
    

    This only works for Java 9 upwards in Java 8 you can use this:

    String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
    List nameList = IntStream.iterate(0, i -> i + 1)
            .limit(names.length)
            .filter(i -> names[i].length() <= i)
            .mapToObj(i -> names[i])
            .collect(Collectors.toList());
    

提交回复
热议问题