java 流中的 groupingBy 方法的问题

问题描述 投票:0回答:1

我必须创建这个方法

getRentals
,给定一本书ID,它应该返回一个
SortedMap<String,String>
。地图的键是读者 ID,值是一个格式为“DD-MM-YYYY DD-MM-YYYY”的字符串,这两个日期代表图书租赁的开始和结束日期。 我写了这段代码,但我遇到了一些问题,我可能还没有很好地理解 groupingBy 是如何工作的......

public SortedMap<String, String> getRentals(String bookID) throws LibException {
    Book b = this.idsColl.get(bookID);

    SortedMap<String, String> res = b.getRentalsList().stream().collect(Collectors.groupingBy(Rental::getReaderId,
            r->{
                String start = r.getStartDate();
                String end = r.getEndDate();
                return start+" "+end;
            }));
    return null;
}

idsColl 是一个映射,我将每个唯一的图书 id 与一个图书对象关联起来。 这些是租赁的属性:

private String readerId;
private String bookId;
private String startDate;
private String endDate;

这些是书籍类的属性:

private String copy_id;
private String title;
private boolean rented=false;
private LinkedList<Rental> rentals = new LinkedList<>();

你能帮我理解我做错了什么吗?

我希望能得到所有租借这本书的读者的地图,该地图与包含租赁开始和结束日期的字符串相关联。 Eclipse 给了我这样的消息:类型

groupingBy(Function<? super T,? extends K>, Collector<? super T,A,D>)
中的方法
Collectors
不适用于参数
(Rental::getReaderId, (<no type> r) -> {})
。 而且 Eclipse 似乎也在责怪 lba 表达式。

java java-stream
1个回答
0
投票

groupingBy
默认返回
HashMap
。您很可能想通过
TreeMap
返回类似
Collectors#groupingBy(Function<T, K>, Supplier<M>, Collector<? super T, A, D>)
的内容:

return b.getRentalsList().stream().Collectors.groupingBy(
        Rental::getReaderId,
        TreeMap::new,
        Collectors.mapping(
            ent -> {
                return /* new map value */;
            },
            Collectors.toList())
        );
© www.soinside.com 2019 - 2024. All rights reserved.