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

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

    String[] namesArray = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
    String completeString
             =  IntStream.range(0,namesArray.length)
               .mapToObj(i -> namesArray[i]) // Converting each array element into Object
               .map(String::valueOf) // Converting object to String again
               .collect(Collectors.joining(",")); // getting a Concat String of all values
            System.out.println(completeString);
    

    OUTPUT : Sam,Pamela,Dave,Pascal,Erik

    String[] namesArray = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
    
    IntStream.range(0,namesArray.length)
                   .mapToObj(i -> namesArray[i]) // Converting each array element into Object
                   .map(String::valueOf) // Converting object to String again
                   .forEach(s -> {
                    //You can do various operation on each element here
                    System.out.println(s);
                   }); // getting a Concat String of all 
    

    To Collect in the List:

    String[] namesArray = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
     List namesList
                    =  IntStream.range(0,namesArray.length)
                    .mapToObj(i -> namesArray[i]) // Converting each array element into Object
                    .map(String::valueOf) // Converting object to String again
                    .collect(Collectors.toList()); // collecting elements in List
            System.out.println(listWithIndex);
    

提交回复
热议问题