用法:
直接上代码
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestCollector {
private List doubleList;
private List integerList;
private List stringList;
@DisplayName("测试返回不可变数组")
@Test
public void testToUnmodifiableList(){
Stream stream = integerList.stream();
//使用Collectors的toUnmodifiableList()方法
List collect = stream.collect(Collectors.toUnmodifiableList());
Assertions.assertThrows(Exception.class,()-> collect.add(1), "没有抛出异常");
System.out.println("抛出了异常");
}
@DisplayName("测试返回平均值")
@Test
public void testAveragingDouble(){
Stream stream = doubleList.stream();
Stream integerStream = integerList.stream();
//求double数组的平均值
Double collect = stream.collect(Collectors.averagingDouble((a) -> a));
System.out.println("double数组的平均值: " +collect);
//把Integer转化为double再求平均值
Double collect1 = integerStream.collect(Collectors.averagingDouble(Integer::doublevalue));
System.out.println("integer数组的平均值: " + collect1);
}
@DisplayName("测试CollectingAndThen")
@Test
public void testCollectingAndThen(){
Stream integerStream = integerList.stream();
//把Integer转化为double再求平均值
Boolean collect = integerStream.collect(Collectors.collectingAndThen(Collectors.averagingInt((a) -> a), (a) -> a > 5));
testAveragingDouble();
System.out.println("integer数组求平均值之后再判断是否>5: " + collect);
}
@DisplayName("测试Counting")
@Test
public void testCounting(){
Stream integerStream = integerList.stream();
Long collect = integerStream.collect(Collectors.counting());
System.out.println("数组个数: " + collect);
}
@DisplayName("测试GroupBy")
@Test
public void testGroupBy(){
Stream integerStream = integerList.stream();
Map