I want to write a loop that references an index with Java 8's Stream API

Everyone loves Stream API, Loops like writing in an extended for statement are clean, but I don't know what to do with a loop that wants to refer to the index inside the loop. (There is a way to create your own class even if you go around: persevere :)

So I twisted my head a little.


The following cases are assumed as "loops that want to refer to the index inside the loop".

――I want to turn two or more lists together --I also want to refer to adjacent elements in one list (such as ʻi-1 or ʻi + 1 for ʻi`)

(Because you can refer to ʻi` and write your favorite process It can also be used in cases such as "I want to change the process at the beginning / end of the list", I think it's not very beautiful. )

Below is a code example.

    public static void main(String[] args) {
        //Appropriate list made of random numbers
        List<Integer> listA = new ArrayList<>(Arrays.asList(12, 23, 66, 45, 10, 48, 21, 25, 68, 65));
        List<Integer> listB = new ArrayList<>(Arrays.asList(98, 96, 4, 33, 30, 38, 39, 25, 32, 64));

        //Case 1: If you want to handle two lists together
        List<Boolean> isWinnerA = IntStream.range(0, Math.min(listA.size(), listB.size()))
                .mapToObj(i -> listA.get(i) > listB.get(i))
                .collect(Collectors.toList());
        System.out.println("isWinnerAList: " + isWinnerAList);
        // -> isWinnerA: [false, false, true, true, false, true, false, false, true, true]

        //Case 2: If you want to handle the front and back of the list together
        List<Double> movingAverage = IntStream.range(0, listA.size() - 1)
                .mapToObj(i -> (listA.get(i) + listA.get(i + 1)) / 2d)
                .collect(Collectors.toList());
        System.out.println("movingAverage: " + movingAverage);
        // -> movingAverage: [17.5, 44.5, 55.5, 27.5, 29.0, 34.5, 23.0, 46.5, 66.5]
    }

As a composition,

--for (int i; i <list.size (); i ++) part --Created with the factory method of ʻIntStream --For a simple increase like the example, you can userange (startInclusive, endExclusive) --If you want to change the magnitude of the increment, you can use ʻiterate (seed, f) .limit (maxSize) (although you can refer to ʻi * 2). --You should be able to do most things with generate (s) --Processing inside the loop --mapToObj (/ * conversion process * /) .collect (/ * aggregate process * /); --If you don't need to aggregate, you can useforEach ()`.


pro: You can write only with the standard ones con: Stream You may be confused if you are not accustomed to it

Is it said that it is better to write in a for sentence normally? Well, if it is the one used in the example, it may be a normal for document, but can it be used in cases such as filter (), aggregation processing, and Stream functions? I think.

Recommended Posts

I want to write a loop that references an index with Java 8's Stream API
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
I want to use java8 forEach with index
I want to ForEach an array with a Lambda expression in Java
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
A story that I struggled to challenge a competition professional with Java
I want to write a nice build.gradle
I want to write a unit test!
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
I tried to make a Web API that connects to DB with Quarkus
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I want to send an email in Java.
I want to simply write a repeating string
I want to write quickly from java to sqlite
I tried to break a block with java (1)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
Rails6 I want to make an array of values with a check box
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
I tried to create a method to apply multiple filters at once with Java Stream API. Is this okay?
I want to monitor a specific file with WatchService
I want to transition screens with kotlin and java!
I want to get along with Map [Java beginner]
I want to return an object in CSV format with multi-line header & filter in Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (gray magic that is not so much as black magic)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Royal road edition that is neither magic nor anything)
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
[Java] I want to convert a byte array to a hexadecimal number
I want to build Java Applet without using an IDE
I want to push an app made with Rails 6 to GitHub
I want to use the Java 8 DateTime API slowly (now)
I want to manually send an authorization email with Devise
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
[Java] Introduction to Stream API
I want to return a type different from the input element with Java8 StreamAPI reduce ()
I want to implement various functions with kotlin and java!
Convert 2D array to csv format with Java 8 Stream API
Convert an array that may be null to a stream
[Java] I want to test standard input & standard output with JUnit
A flowing interface? -I want to give you an opportunity to write good code. 3 [C # refactoring sample]
I want a quick test S3. Start minio with docker-compose and create a state with an initial bucket.
How to deal with the type that I thought about writing a Java program for 2 years
I tried to create an API to get data from a spreadsheet in Ruby (with service account)
I want to make a button with a line break with link_to [Note]
I want to convert an array to Active Record Relation with Rails
I want to add a browsing function with ruby on rails
I just want to write Java using Eclipse on my Mac
I want to return to the previous screen with kotlin and java!
[Ruby] I want to put an array in a variable. I want to convert to an array
How to implement a job that uses Java API in JobScheduler
How to deploy an app that references a local jar to heroku
I tried to make an Android application with MVC now (Java)
[Java] I want to perform distinct with the key in the object
I want to extract between character strings with a regular expression
Want to throw an IOException out of Stream? in that case
[java8] To understand the Stream API
[Introduction to Java] About Stream API
I tried to interact with Java
I tried using Java8 Stream API