无法推断hashmap的类型参数<>

时间:2017-11-23 07:17:26

标签: java java-8 hashmap java-stream

我正在

   Cannot infer type arguments for java.util.HashMap<>

以下代码

class Test {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "x");
        map.put(2, "y");
        map.put(3, "x");
        map.put(4, "z");

  //the following line has error
        Map<String, ArrayList<Integer>> reverseMap = new java.util.HashMap<>(map.entrySet().stream()
                .collect(Collectors.groupingBy(Map.Entry::getValue)).values().stream()
                .collect(Collectors.toMap(item -> item.get(0).getValue(),
                        item -> new ArrayList<>(item.stream().map(Map.Entry::getKey).collect(Collectors.toList())))); 
        System.out.println(reverseMap);

    }

}

出了什么问题,谁能解释一下这个? 我检查了正确的导入,发现我正在导入java.util.hashmap而不是其他。 仍然令人讨厌的错误正在惹恼我。

The Error Persists

3 个答案:

答案 0 :(得分:6)

这是ecj(eclipse编译器)中的一个错误,您可以解决它并添加更多类型信息:

item -> new ArrayList<Integer>(item.stream().map(Entry::getKey)

了解我如何添加ArrayList<Integer>

使用javac-8 and 9编译好。

顺便说一句,似乎有一种更简单的方法:

map.entrySet()
            .stream()
            .collect(Collectors.groupingBy(
                    Entry::getValue,
                    HashMap::new,
                    Collectors.mapping(Entry::getKey, Collectors.toList())));

答案 1 :(得分:1)

就我而言,添加import java.util.Map;后,错误消失了:

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import com.fasterxml.jackson.databind.ObjectMapper;


    public void saveFooOrder(Foo foo, long orderId) {

         Map<String, Object> values = new HashMap<>();
                                         /*^^^^ Error was here: Cannot 
                                                infer type arguments for HashMap<>*/
            values.put("fooOrder", orderId);
            values.put("foo", foo.getId());
            orderFooInserter.execute(values);   
    }

答案 2 :(得分:0)

您的代码未完成,而您错过了)

尝试做:

import java.util.*;
import java.util.stream.Collectors;
public class HelloWorld{

     public static void main(String []args){
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "x");
        map.put(2, "y");
        map.put(3, "x");
        map.put(4, "z");

        Map<String, ArrayList<Integer>> reverseMap = new java.util.HashMap<>(map.entrySet().stream()
                .collect(Collectors.groupingBy(Map.Entry::getValue)).values().stream()
                .collect(Collectors.toMap(item -> item.get(0).getValue(),
                        item -> new ArrayList<>(item.stream().map(Map.Entry::getKey).collect(Collectors.toList())))));
        System.out.println(reverseMap);
     }
}

这会产生输出

{x=[1, 3], y=[2], z=[4]}
相关问题