如何从列表(列表内)获取最小值

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

我的 Java 有问题。 我有这个 json。

[
     {
         "customObject": "item 1",
         "list": [
             {
                 "method": "p1",
                 "price": "1000"
             },
             {
                 "method": "p2",
                 "price": "220"
             },
             {
                 "method": "p3",
                 "price": "3400"
             }
         ]
     },
     {
         "customObject": "item 2",
         "list": [
             {
                 "method": "p4",
                 "price": "5000"
             },
             {
                 "method": "p5",
                 "price": "1"
             },
             {
                 "method": "p6",
                 "price": "98752326"
             }
         ]
     }
]

我要最低价

目标是找到所有字段价格中的最小值。在这种情况下,我会得到值 1,仅得到值。

我尝试了这段代码,但我对此不太满意

OptionalDouble min = list.stream()
                     .flatMap(e -> e.getList().stream())
                     .mapToDouble(v -> Double.parseDouble(v.getPrice().replace(" ", "").replace(",", ".")))
                     .min();

有人可以帮助我吗?

java stream min
1个回答
0
投票

从你的代码片段中我假设你解码的 Java 类看起来像这样

public class Entity {
    private String customObject;
    private List<Pair> list;
    public Entity(String customObject) {
        this.customObject = customObject;
        this.list = new ArrayList<>();
    }

    public String getCustomObject() {
        return customObject;
    }

    public List<Pair> getList() {
        return list;
    }

    public void setCustomObject(String customObject) {
        this.customObject = customObject;
    }

    public void setList(List<Pair> list) {
        this.list = list;
    }
}

class Pair {
    String method;
    String price;

    public Pair(String method, String price) {
        this.method = method;
        this.price = price;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

其中

price
是字符串格式,并且您有一个
Entity
列表。在这种情况下,你可以使用这个过滤器

Double min = list.stream().mapToDouble(e -> e.getList().stream()
                .mapToDouble(v -> Double.parseDouble(v.getPrice().replace(" ", "").replace(",", ".")))
                .min().orElse(-1)).min().orElse(-1);

在这里,我使用

-1
作为占位符值,以防列表为空(假设
price
不能为负数)。您可以使用其他值。您甚至可以使用
orElseThrow()
而不是
orElse()

引发异常
© www.soinside.com 2019 - 2024. All rights reserved.