有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将返回类型强制为泛型类型,而不是对象类型,以便使用收集器和流构建映射

我正在尝试从List<Pair<GraphNode<Character>, List<String>>>对构造Map<String, GraphNode<Character>>。但我所面临的问题是,它给出了错误的说法,类型不匹配:无法将Map<Object,Object>转换为Map<String,GraphNode<Character>>

我应该如何强制返回Map<String,GraphNode<Character>>

List<Pair<GraphNode<Character>, List<String>>> pairs = lines.stream().map(line -> {
            String[] split = line.split(":");
            List<String> dest = Lists
                    .newArrayList(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(split[1]));
            GraphNode<Character> node = new GraphNode<>(split[0].toCharArray()[0]);
            return new javafx.util.Pair<GraphNode<Character>, List<String>>(node, dest);
        }).collect(Collectors.toList());
Map<String, GraphNode<Character>> graphMap = pairs.stream().map(pair -> pair.getKey())
                    .collect(Collectors.toMap(GraphNode::getData, pair -> pair));

共 (2) 个答案

  1. # 1 楼答案

    因为您的类有Character类型(GraphNode<Character>),所以我认为GraphNode::getData也会返回Character相关类型

    但是您在Map<String, GraphNode<Character>>中将其分配给了String,因此会出现类型不匹配

    解决方案是将GraphNode::getData映射到字符串

  2. # 2 楼答案

    您的map步骤是错误的,因为您正在丢弃List<String>(即Pair的值部分)中的数据,我假设您希望该数据位于输出映射中。我建议使用flatMapStream<Pair<GraphNode<Character>, List<String>>>转换为Stream<Pair<GraphNode<Character>, ListString>>。从那里,得到一个Map<String, GraphNode<Character>>是微不足道的

    Map<String, GraphNode<Character>> graphMap =
        pairs.stream()
             .flatMap(pair->pair.getValue().stream().map(s -> new javafx.util.Pair<GraphNode<Character>, String>(pair.getKey(), s)))
             .collect(Collectors.toMap(Pair::getValue,Pair::getKey));