-1

How can I make this work? Trying to throw an exception as the default thing to do if the map does not containt the key but editor says "The target type of this expression must be a functional interface":

cliente.setMIMECode(CertificationsConstants.FILE_TYPES.getOrDefault(
    uploadCertificateSchoolRequest.getTypeFile(), 
    () -> { throw new IllegalStateException("unkonwn filetype"); }
));
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
BugsOverflow
  • 386
  • 3
  • 19
  • 2
    Look [here](https://stackoverflow.com/q/42408264/102937). – Robert Harvey Jun 06 '22 at 16:26
  • 1
    Use `computeIfAbsent`. – Johannes Kuhn Jun 06 '22 at 16:28
  • 2
    `#getOrDefault` expects a value, not a lambda/functional interface. @JohannesKuhn is right in that you would use `#computeIfAbsent` here, though if the `Map` should also not contain a `null` value you could simply `#get` from the `Map` and null-check the return value. – Rogue Jun 06 '22 at 16:32
  • 1
    MIMEcode isn't represented as a *function*, `getOrDefault()` expects a *key* and a *default value*. Makes sense? Hence, your code is incorrect. As it has been already suggested, use `computeIfAbsent()` instead: `map.computeIfAbsent("key", k -> {throw new IllegalStateException();});` – Alexander Ivanchenko Jun 06 '22 at 16:39

1 Answers1

2

getOrDefaults signature is getOrDefault(K, V), not getOrDefault(K, Supplier<V>). You want to use Map#computeIfAbsent which accepts a Function<? super K, ? extends V> as second argument to compute a value in the case of an absent key.

That said, it feels wrong to (ab)use computeIfAbsent for this. Why not simply check the result, once retrieved from the map?

final var fileType = CertificationsConstants.FILE_TYPES.get(
    uploadCertificateSchoolRequest.getTypeFile());
if (fileType == null) {
  throw new IllegalStateException("unknown filetype");
}
cliente.setMIMECode(fileType);

Or, if you don't require this exact exception type, the following:

cliente.setMIMECode(
    Objects.requireNonNull(
        CertificationsConstants.FILE_TYPES.get(
            uploadCertificateSchoolRequest.getTypeFile(),
            "unknown filetype")));
knittl
  • 246,190
  • 53
  • 318
  • 364
  • I wanted to do the check if null but I though it would be better to have everything in 1 line with a lambda, could you explain a little what the second option does? Will it throw a nullpointerexception with the unknown filetype as message? – BugsOverflow Jun 06 '22 at 16:57
  • @BugsOverflow yes exactly, it will throw a NullPointerException with the provided message. – knittl Jun 06 '22 at 17:04