不废话直接上代码
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<GetDateRequest> 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<String, Optional<GetDateRequest>> optionalMap = list.stream().collect(Collectors.groupingBy(GetDateRequest::getVersion, Collectors.maxBy(Comparator.comparing(GetDateRequest::getId))));
Set<GetDateRequest> 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/