【问题标题】:Android about stream apiAndroid关于stream api
【发布时间】:2016-05-11 17:30:37
【问题描述】:

我想在我的项目 Lightweight-Stream-APIRetroLambda 上使用流 api

代码:

Map<String, Object> liste = new HashMap<>();
for (Map.Entry<String, ?> data : tumListe.entrySet()) {
    try{
        if (data.getValue() != null) {
            if(data.getValue() instanceof String){
                try {
                    liste.put(data.getKey(), new Gson().fromJson(((String) data.getValue()), new TypeToken<List<String>>(){}.getType()));
                }catch (JsonIOException ignored){
                    continue;
                }catch (JsonParseException ignored){
                    continue;
                }
            }

            liste.put(data.getKey(), data.getValue());
        }
    } catch (NullPointerException | ClassCastException ignored) {}
}

如何重构此代码以使用流,例如Stream.of()方法?

【问题讨论】:

    标签: android hashmap java-stream


    【解决方案1】:

    Stream.of 采用 List/Iterator/Iterable,因此您可以简单地编写 Stream.of(hashMap.entrySet())Stream.of(hashMap) 并使用 Stream API 迭代映射条目。接下来可以只过滤非空值filter(entry -&gt; entry.getValue() != null),在forEach方法中进行操作。

    要跳过不必要的 try/catch 块,请使用 Exceptional 类(仅限 LSA 功能)。

    代码:

    Map<String, Object> liste = new HashMap<>();
    Stream.of(tumListe)
            .filter(data -> data.getValue() != null)
            .forEach(data -> Exceptional.of(() -> {
                if (data.getValue() instanceof String) {
                    liste.put(data.getKey(), new Gson().fromJson((String) data.getValue()));
                } else {
                    liste.put(data.getKey(), data.getValue());
                }
                return null; // irrelevant, for Exceptional result
            }));
    

    【讨论】:

      猜你喜欢
      • 2011-02-25
      • 1970-01-01
      • 2016-07-06
      • 2017-08-13
      • 2011-08-28
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多