Stream系列(八)Reduce方法使用

裁减计算
视频讲解: https://www.bilibili.com/vide...
image

EmployeeTestCase.java

package com.example.demo;

import lombok.Data;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;
import one.util.streamex.StreamEx;
import org.junit.Test;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Log4j2
public class EmployeeTestCase extends BaseTestCase{
    @Test
    public void distinct() {
        //常规实现方式
        List employeesDis = list.stream().distinct().collect(Collectors.toList());
        assertEquals(employeesDis.size(),5);
        //StreamEx 实现方式
        List employeesDisBySalary2 = StreamEx.of(list).distinct(Employee::getSalary)
                .peek(System.out::println).collect(Collectors.toList());
        //Stream filter 实现方式
        List employeesDisBySalary = list.stream().filter(distinctByKey(Employee::getSalary))
                .collect(Collectors.toList());
        assertEquals(employeesDisBySalary,employeesDisBySalary2);
    }
    private static  Predicate distinctByKey(Function keyExtractor) {
        Map seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

BaseTestCase.java

package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class BaseTestCase {
    protected static final List list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));
}

关注公众号,坚持每天3分钟学习
image

你可能感兴趣的:(java,stream,reduce)