我需要根据最新日期删除重复项。
class Stat {
private String country;
private String state;
private String fullname;
Date indepdate;
public Stat(String country,String state,String fullname,int indepdate){
this.country=country;
this.state=state;
this.fullname=fullname;
this.indepdate=indepdate;
}
//also getters and setters
public String toString() {
return "("+country+","+state+","+fullname+","+indepdate+")";
}
}
ArrayList<Stat> stats =new ArrayList();
Stats.add(new Stat("USA", "Florida", "John Jones", 5/1/2020));
Stats.add(new Stat("USA", "Florida", "Jeff Cane", 4/1/2016));
Stats.add(new Stat("USA", "California", "Lisa Smith", 3/1/2000));
Stats.add(new Stat("Germany", "Florida", "Tom Joseph", 5/1/2019));
Stats.add(new Stat("Germany", "Florida", "Chris Richard", 5/1/2018));
Stats.add(new Stat("Germany", "California", "Nancy Diaz", 4/3/2015));
我需要删除重复的国家,只保留最新日期的国家。
列表应如下所示:
USA, florida, John James, 5/1/2020
Germany,Florida,Tom Joseph, 5/1/2019
到目前为止,我有以下几点:
Map<String, Map<String, List<Stat>>
groupByCountryAndCity = stats.
stream().
collect(
Collectors.
groupingBy(
Stat::getCountry,
Collectors.
groupingBy(
Stat::getIndepdate
)
)
);
3条答案
按热度按时间roqulrg31#
你可以用
LocalDate
为了indepdate
现场。然后使用
LocalDate.of()
方法:LocalDate.of(2020, 5, 1)
试试这个:输出:
mrphzbgm2#
您可以使用以下方法
Collectors
方法:groupingBy(Function<> classifier, Collector<> downstream)
collectingAndThen(Collector<> downstream, Function<> finisher)maxBy(Comparator<> comparator)
```List stats = Arrays.asList(
new Stat("USA", "Florida", "John Jones", "5/1/2020"),
new Stat("USA", "Florida", "Jeff Cane", "4/1/2016"),
new Stat("USA", "California", "Lisa Smith", "3/1/2000"),
new Stat("Germany", "Florida", "Tom Joseph", "5/1/2019"),
new Stat("Germany", "Florida", "Chris Richard", "5/1/2018"),
new Stat("Germany", "California", "Nancy Diaz", "4/3/2015") );
Map<String, Stat> result = stats.stream()
.collect(Collectors.groupingBy(Stat::getCountry,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Stat::getIndepdate)),
Optional::get)));
result.values().forEach(System.out::println);
class Stat {
private final String country;
private final String state;
private final String fullname;
private final LocalDate indepdate;
}
(USA,Florida,John Jones,2020-05-01)
(Germany,Florida,Tom Joseph,2019-05-01)
rnmwe5a23#
yu可以使用收集器提供的流的减少。像这样的东西: