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 use
range (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 use
forEach ()`.
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