reduce:是指能够把一个流缩减成一个值,能实现对集合求和,求乘积,求最值等操作
package com.ydlclass.feature;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class LambdaTest {
List<Person> personList = new ArrayList<>();
List<Integer> simpleList = Arrays.asList(15,22,9,11,33,52,14);
@Before
public void initData(){
personList.add(new Person("张三",3000,23,"男","太原"));
personList.add(new Person("李四",7000,34,"男","西安"));
personList.add(new Person("王五",5200,22,"女","西安"));
personList.add(new Person("小黑",1500,33,"女","上海"));
personList.add(new Person("狗子",8000,44,"女","北京"));
personList.add(new Person("铁蛋",6200,36,"女","南京"));
}
@Test
public void reduceTest(){
int reduce = IntStream.of(1, 3, 9, 2, 5).reduce(1, new IntBinaryOperator() {
//学了一个新函数是接口,identity可以理解为一个初始值,left表示每次的结果,right代表前面的流遍历的数字;
//于是此处实现了一个阶乘的使用,最后的结果会重新赋值给left
@Override
public int applyAsInt(int left, int right) {//分别代表当前的数字,结果
return left * right;
}
});
System.out.println(reduce);
int reduce1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8).reduce(0, (n1, n2) -> n1 + n2);
int reduce2 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8).reduce(0, Integer::sum);
}
@Test
public void joinTest(){
List<String> list = Arrays.asList("a", "b", "v");
String collect = list.stream().collect(Collectors.joining("-"));//collect会收集之前的内容,使用-连接
String collect1 = String.join("-", list);//collect会收集之前的内容,使用-连接
System.out.println(collect1);
System.out.println(collect);
}
}