gpt4 book ai didi

java - 使用 Java Stream API 进行分层过滤

转载 作者:行者123 更新时间:2023-12-05 09:36:26 24 4
gpt4 key购买 nike

我有一些命令式 Java 条件代码,我想重构它们以使用 Streams。

具体来说,我有这张 map ,我想根据特定的过滤条件将其过滤到列表中。

private  Map<Integer,Thing> thingMap = new HashMap<Integer,Thing>();
// populate thingMap

下面是使用它的代码:

List<Thing> things = new ArrayList<Thing>();

for (Thing thing : thingMap.values()) {
if (thing.getCategory().equals(category)) {
if (location == null) {
things.add(thing);
} else if (thing.getLocation().equals(location)) {
things.add(thing);
}
}
}

我将其重构为以下内容。但缺少的是,如果类别过滤器通过,我希望检查位置。另外,我怀疑有更好的方法可以做到这一点:

List<Thing> things = thingMap.entrySet()
.stream()
.filter(t -> t.getValue().getCategory().equals(category))
.filter(t ->
location == null ||
t.getValue().getLocation().equals(location)
)
.map(Map.Entry::getValue)
.collect(Collectors.toList());

使用 Streams 保留分层条件检查的惯用方法是什么?

最佳答案

filter 之后链接的操作只会对谓词接受的元素执行。所以没有必要担心这一点。

您还可以将条件加入到单个 filter 中步骤,就像您可以加入嵌套的 if语句合并为单个 if , 通过使用 && 组合条件.结果是一样的。

但请注意,循环使用条件 location == null ,指的是在您发布的代码片段之外声明的变量,而不是 thing.getLocation() == null .

除此之外,与循环相比,您还进行了其他不必要的更改。循环遍历 values()您使用 entrySet() 时的 map View 相反,对于 Stream,需要调用 getValue()Map.Entry 上四次。

循环逻辑的直接翻译要简单得多:

List<Thing> things = thingMap.values().stream()
.filter(thing -> thing.getCategory().equals(category))
.filter(thing -> location == null || thing.getLocation().equals(location))
.collect(Collectors.toList());

关于java - 使用 Java Stream API 进行分层过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65131714/

24 4 0