2018-05-22 java 8 lambda List 过滤重复Object对象 根据特定field属性

不废话直接上代码

实体类

package com.example.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @author albert on 5/22/2018
 */
@Data
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class GetDateRequest {

    String id;
    String Version;
    Date requestTime;

}

方法

package com.example.demo;

import com.example.entity.GetDateRequest;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.stream.Collectors;

@RunWith(SpringRunner.class)
@SpringBootTest
@Log4j2
public class DemoApplicationTests {

    @Test

    public void contextLoads() {

        List list = new ArrayList();

        list.add(new GetDateRequest("1", "0001", new Date()));
        list.add(new GetDateRequest("2", "0001", new Date()));
        list.add(new GetDateRequest("3", "0001", new Date()));
        list.add(new GetDateRequest("4", "0002", new Date()));
        list.add(new GetDateRequest("5", "0001", new Date()));

        Map> optionalMap = list.stream().
collect(Collectors.groupingBy(
GetDateRequest::getVersion, 
Collectors.maxBy(Comparator.comparing(GetDateRequest::getId))));

        Set getDateRequestSet = 
optionalMap.values().stream().
map(x -> x.get())
.collect(Collectors.toSet());

        getDateRequestSet.stream().forEach(x -> log.debug(x));

        getDateRequestSet.stream().forEach(x -> System.out.println(x));

    }

}

结果

GetDateRequest(id=5, Version=0001, requestTime=Tue May 22 22:59:58 SGT 2018)
GetDateRequest(id=4, Version=0002, requestTime=Tue May 22 22:59:58 SGT 2018)

参考代码

原文出处
https://blog.csdn.net/Java_HuiLong/article/details/59056611
https://www.javabrahman.com/java-8/java-8-finding-maxmin-with-collectors-maxby-minby-methods-tutorial-with-examples/

你可能感兴趣的:(2018-05-22 java 8 lambda List 过滤重复Object对象 根据特定field属性)