如何在流api中显示必须具有最小字段的有限数量的记录?

How to display a limited number of records that must have a minimal field in stream api?

我有一个流,我想显示速率最低的五个记录。我明白我需要先使用排序,然后使用 limit() 方法显示尽可能多的元素。但是,我不明白如何实现它。

   Stream <Collection <Logs>> stre = Stream.of(firstCollection, lastCollection);
        stre.flatMap(Collection::stream).collect(Collectors.groupingBy(Logs::getId,
                Collectors.mapping(Logs::getTime,
    Collectors.toList())))
   .forEach ((id, list) -> {});

我需要这个输出:

比如我要选人

Jasmine, seller, 31          
Andry, blogger, 12
Samanta, model, 16 
Mike, programmer, 20
Debby, seller, 19
Mark, artist, 12
...

more than 100 records

我想 select 15-18 岁的人,我希望样本中的最大人数为 3

Mark, artist, 12
Andry, blogger, 12
Samanta, model, 16 

如何使用流实现这个逻辑API?

如果我们谈论的是人的例子,我会使用谓词来获取包含在所需年龄范围内的人的子列表,应用排序然后应用限制:

entries.stream()
    .filter(x -> x.getAge() >= 15 && x.getAge() <= 18)
    .sorted(Comparator.comparingInt(Entry::getAge))
    .limit(3)
    .collect(Collectors.toList())

I have a stream and I want to display the five records with the lowest rate. I understand that i need to first use sorting, and then use the limit.

我可以帮助您满足上述要求。但是过滤 15 到 18 岁之间的年龄对于显示的输出没有意义。

  • 不清楚你的记录是年龄还是时间。
  • 您在上面指定了 5 条记录,但您的输出只显示了 3 条

我建议不要使用 limit。您已经对列表进行了排序,所以为什么不保留它并打印 subList。我创建了两个 Lists 来开始重现您在问题中的内容。请注意,我使用的是 record(在 Java 15 中介绍)而不是 class,因为它更容易编码,但您的 class 应该可以正常工作替换。请注意,我可能错误地重命名了 class 和吸气剂。

record Logs(String getName, String getJob, int getTime) {
    @Override
    public String toString() {
        return getName + ", " + getJob + ", " + getTime;
    }
}

现在创建两个列表。


List<Logs> firstCollection =
        List.of(new Logs("Jasmine", "seller", 31),
                new Logs("Andry", "blogger", 12),
                new Logs("Samanta", "model", 16));
List<Logs> lastCollection =
        List.of(new Logs("Mike", " programmer", 20),
                new Logs("Debby", "seller", 19),
                new Logs("Mark", "artist", 12));

并计算排序后的列表。

List<Logs> result = Stream.of(firstCollection, lastCollection)
        .flatMap(List::stream)
        .sorted(Comparator.comparing(Logs::getTime))
        .toList(); // java 16 or .collect(Collectors.toList());

现在只需使用排序列表的标准索引范围打印 subList

result.subList(0,3).forEach(System.out::println);

打印(如您的问题所示)

Andry, blogger, 12
Mark, artist, 12
Samanta, model, 16

但是如果你真的不需要排序后的值,那么...

List<Logs> result = Stream.of(firstCollection, lastCollection)
        .flatMap(List::stream)
        .sorted(Comparator.comparing(Logs::getTime))
        .limit(3)
        .toList(); // java 16 or .collect(Collectors.toList());

然后正常打印列表。