【问题标题】:Collect to treemap java 8收集到树形图 java 8
【发布时间】:2018-11-03 13:16:44
【问题描述】:

我想通过处理将结果收集到TreeMap<Integer,Double> TreeMap<Integer,ArrayList<String>>.

TreeMap<Integer,Double> result2 = units.entrySet().stream()
                                        .filter(v -> v.getValue().size()>3)
                                        .filter(v -> !v.getValue().get(1).isEmpty() && !v.getValue().get(2).isEmpty())
                                        .mapToDouble(v -> mult( v.getValue().get(1), v.getValue().get(2)))
                                        .collect();

基本上我所做的是我从流中的字符串的 ArrayList 中获取值,并过滤掉没有值的值,并通过在 lambda 表达式中使用 mult 函数来获得第二个和第三个元素的乘积。现在我不知道如何收集到 TreeMap,其中键是处理后的 TreeMap 的键,称为单位,值应该是我在 mapToDouble 中计算的乘积。

注意:单位是TreeMap&lt;Integer,ArrayList&lt;String&gt;&gt;

【问题讨论】:

    标签: java lambda treemap collect


    【解决方案1】:

    您可以使用 toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) 方法的重载版本将数据收集到 TreeMap,该方法允许您指定要创建的 Map。

    TreeMap<Integer,Double> result2 = units.entrySet().stream()
                        .filter(v -> v.getValue().size()>3)
                        .filter(v -> !v.getValue().get(1).isEmpty() && !v.getValue().get(2).isEmpty())
                        .collect(Collectors.toMap(
                                entry -> entry.getKey(),
                                entry-> mult( entry.getValue().get(1), entry.getValue().get(2)),
                                (entry1, entry2) -> entry1, // called if duplicate keys are there, I have return entry1 by default by you can modify it according to you
                                TreeMap::new
                        ));
    

    你可以参考这个来查看 toMap 方法的重载。 https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 2015-02-24
      • 2016-08-19
      • 2019-02-17
      • 2017-07-03
      相关资源
      最近更新 更多