代码之家  ›  专栏  ›  技术社区  ›  Maurice

为什么平面映射和收集树集列表会返回对象?

  •  0
  • Maurice  · 技术社区  · 6 年前

    我正在尝试将具有treeset的列表的所有值treeset元素放入 linkedHashSet . 此树集列表由 values() A方法 TreeMap<String, TreeSet> . 代码如下:

    Map<String, TreeSet> sortedByMonthAndVarietyNameMap = new HashMap<>();
        sortedByMonthAndVarietyNameMap.values().stream().flatMap(monthList -> monthList.stream()).collect(Collectors.toCollection(LinkedHashSet::new));
    

    这应该是返回 LinkedHashSet 具有平面映射树集的所有元素。但实际上它返回一个类型的对象 Object .

    为什么会这样?有人能解释我做错了什么吗?

    3 回复  |  直到 6 年前
        1
  •  4
  •   Holger    6 年前

    TreeSet未完全键入:

    Map<String, TreeSet<Integer>> sortedByMonthAndVarietyNameMap = new HashMap<>();
    LinkedHashSet<Integer> result = sortedByMonthAndVarietyNameMap.values().stream()
            .flatMap(monthList -> monthList.stream())
            .collect(Collectors.toCollection(LinkedHashSet::new));
    
        2
  •  0
  •   superz600    6 年前

    这是你想要的吗?

    LinkedHashSet<TreeSet> collect = sortedByMonthAndVarietyNameMap
        .values()
        .stream()
        .flatMap(Stream::of)
        .collect(Collectors.toCollection(LinkedHashSet::new));
    

    另外,这种数据转换看起来很奇怪。也许你可以更详细地描述一下你的案件?

        3
  •  0
  •   Gaurav Srivastav    6 年前

    因为您在未指定类型的情况下提供了LinkedHashSet的构造函数引用。

    https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13