Hi tried to figure out how to map to a EnumMap without success. At the moment I'm doing it in 2 steps, I create the map and then I make it a EnumMap. Question are.
From efficiency perspective would be better to get Values from input, make them a set and then stream it, or just using toMap as its right now is correct. thanks
Map<CarModel, CarBrand> input...
final Map<CarBrand, CarsSellers> ret = input.values()
.stream().filter(brand -> !brand.equals(CarBrand.BMW))
.collect(toMap(Function.identity(), brand -> new CarsSellers(immutableCars, this.carsDb.export(brand))));
final EnumMap<CarBrand, CarsSellers> enumMap = new EnumMap<>(CarBrand.class);
enumMap.putAll(ret);
toMap
method.By default a toMap
uses HashMap::new
as the Supplier<Map>
- you need to supply a new EnumMap
instead.
final Map<CarBrand, CarsSellers> ret = input.values()
.stream()
.filter(brand -> brand != CarBrand.BMW)
.collect(toMap(
identity(),
brand -> new CarsSellers(immutableCars, this.carsDb.export(brand)),
(l, r) -> {
throw new IllegalArgumentException("Duplicate keys " + l + "and " + r + ".");
},
() -> new EnumMap<>(CarBrand.class)));
Arguments are:
key
extractorvalue
extractorMap
and one to be added. In this case, we simply throw an IllegalArgumentException
as keys should be uniqueEnumMap
.Notes on your code:
interface
- Map
not EnumMap
enum
is singleton, so you can use a != Enum.VALUE
import static
for Function.identity()
makes things less verboseIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With