代码之家  ›  专栏  ›  技术社区  ›  Alex Bloomberg

使用Java流生成json对象

  •  -1
  • Alex Bloomberg  · 技术社区  · 7 年前

    我使用的API包含以下格式的信息:

    [
    {Key1: Value1,
     Key2: Value2A,
     Key3: Value3A,
     Key4: Value4A},
    {Key1: Value1,
     Key2: Value2B,
     Key3: Value3B,
     Key4: Value4B},
    {Key1: Value1,
     Key2: Value2C,
     Key3: Value3C,
     Key4: Value4C}
    ]
    

    我正在尝试根据Key2的值获取Key3的值。我知道Key2的值是什么,但Key3的值是在运行时生成的。我想比较Key2的值,如果匹配,则从该对象返回Key3的值。

    我在网上通读了有关streams的内容后尝试使用它,但我既无法获取整个对象,也无法获取作为字符串的特定值。

    以下是我尝试过的,但完全没有结果:

    public static String fetchCarModel(String value2A) {
    
        final Optional<CarModel> carModel =  Car.api().models().list().stream()
                .filter(r -> r.getKey().equals(value2A)) // Check for the correct object
                .findAny();
    
        return carModel.get().getId();
    }
    

    感谢您的帮助。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ousmane D.    7 年前

    看来 Car.api().models().list() 返回a List<CarModel> 哪里 CarModel 具有上述四个属性。

    在这种情况下,为了达到上述要求,您可以执行以下操作:

    public static String fetchCarModel(String value2A) {    
        final Optional<CarModel> carModel =  Car.api().models().list().stream()
                .filter(carModel -> carModel.getKey2().equals(value2A)) // Check for the correct object
                .findAny();   
    
        return carModel.get().getKey3(); // get the value of this property
    }
    

    注意,您应该只打电话 Optional.get() 如果您确定 Optional<T> 否则,最好利用 orElse orElseGet 要展开值(如果存在),请提供默认值。

    理想情况下,更好的方法是更改方法签名以返回 Optional<String> 然后让此API的调用方决定在无值情况下要做什么。