Manipulating List with java8StreamAPI :: reduce

Processing that divides processing according to the index of List, which is common in business logic, can also be implemented using reduce. For example "Add: to other than the beginning of the list" Logic such as can be implemented as follows using reduce

MyBusinessLogic.java


package test;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Stream;

public class MyBunessLogic {
	public static void main(String args[]){
		final BiFunction<List<String>, String, List<String>> operation = 
	            (accum, value) -> {
	            	if(accum.size()!=0)accum.add(" : "+value);
	            	else accum.add(value);
	                return accum;
	    };
	    Stream.of("start","middle","end")
	    .reduce(new ArrayList<String>(),operation,(s,v)->s)
	    .forEach(System.out::print);
	}
}
Output result
start : middle : end

Postscript The meaning of the BiFunction type is difficult to understand, so make a note of its use. The first and second types of generics are the types of function arguments, the first is the accumulator, and the second is the value to be operated on. The third type of generic shows the return value when the function is executed

Addendum 2 The lambda expression passed to the third argument of reduce is called when the pararell method of the Stream class is executed, but in the sample example, an appropriate expression is given. This is because the above example is intended to process Lists in order, not to process them in parallel. Personally, I think it would be convenient if the reduce method had an overload of (U indentity, BiFunction \ <U, T, U > func), a method that is not intended for parallel operation.

Addendum 3 In the above example, the variable (accum) passed as the argument of the lambda expression is destructively operated, so I will write an improved version.

MyBunessLogic.java


package test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class MyBunessLogic {
	public static void main(String args[]){
	    Stream.of("start","middle","end")
	    .reduce(new ArrayList<String>(),MyBunessLogic::operate,(s,v)->s)
	    .forEach(System.out::print);
	}
	
	private static  List<String> operate(List<String> accum,String value){
		List<String> list = new ArrayList<String>(accum);
    	if(list.size()!=0)list.add(" : "+value);
    	else list.add(value);
        return list;
	}
}



Recommended Posts

Manipulating List with java8StreamAPI :: reduce
Reduce verbose code with Lombok
Try manipulating PostgreSQL arrays with JDBC
Make a list map with LazyMap
[Java] Reduce if statements with Enum
Test list inclusion relationships with AssertJ
Java8 list conversion with Stream map