Cha*_*war 3 java hashmap java-8 java-stream
我正进入(状态
Cannot infer type arguments for java.util.HashMap<>
Run Code Online (Sandbox Code Playgroud)
对于以下代码
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);
}
}
Run Code Online (Sandbox Code Playgroud)
出了什么问题,谁能解释一下这个?我检查了正确的导入,发现我正在导入java.util.hashmap而不是其他.仍然令人讨厌的错误正在惹恼我.
这是ecj(eclipse编译器)中的一个错误,您可以解决它并添加更多类型信息:
item -> new ArrayList<Integer>(item.stream().map(Entry::getKey)
Run Code Online (Sandbox Code Playgroud)
看看我是如何添加的ArrayList<Integer>.
它编译得很好javac-8 and 9.
顺便说一句,似乎有一种更简单的方法:
map.entrySet()
.stream()
.collect(Collectors.groupingBy(
Entry::getValue,
HashMap::new,
Collectors.mapping(Entry::getKey, Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
就我而言,添加后错误消失了 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10038 次 |
| 最近记录: |