I know the title is weird, I had no idea what else to write. I'm relatively new to java so I apologize if this is something very basic. I've tried my best to explain the point through code. The question here is -
This compiles,
// WAY 1
Map<MyType, MyType> myMap = (Map) new MyMap();
This does not,
// WAY 2
Map<MyType, MyType> myMap2 = (Map<MyType, MyType>) new MyMap();
Firstly, why such behavior. And secondly, way 2 allows me to write my wanted code in one line as written in method WhatIWant, while way 1 does not, again as written in method WhatIWant. Can I write that code in one line? If yes, how. If not, why not.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
// A class not created by me but in a library so i cannot use generic types as i cannot change stuff here
class MyMap extends LinkedHashMap<Object, Object> {
}
// has methods which i need for processing on myMap
class MyType {
int myMethod() {
return -1;
}
}
class Scratch {
public static void main(final String[] args) throws Exception {
// WAY 1:
// compiles
// WARNING : Unchecked assignment: 'java.util.Map' to 'java.util.Map<MyType, MyType>'
Map<MyType, MyType> myMap = (Map) new MyMap();
// WAY 2:
// does not compile
// ERROR: Inconvertible types; cannot case 'MyMap' to 'java.util.Map<MyType, MyType>'
Map<MyType, MyType> myMap2 = (Map<MyType, MyType>) new MyMap();
}
public static void WhatIWant() {
// to be able to write code below in one line
Map<MyType, MyType> myMap = (Map) new MyMap();
myMap.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toString(),
entry -> entry.getValue().myMethod()
));
// I thought it would work if i used WAY 2 like
((Map<MyType, MyType>) new MyMap()).entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toString(),
entry -> entry.getValue().myMethod()
));
// but as you saw above in WAY 2, it does not compile, how can i do this in one line
}
}