Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java8 Collectors.toMap() limitation?

I am trying to use java8's Collectors.toMap on a Stream of ZipEntry. It may not be the best idea because of possible exceptions occuring during the processing, but I guess it ought to be possible.

I am now getting a compile error (type inference engine I guess) which I don't understand.

Here's some extracted demo code:

import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class TestMapCollector {

    private static class MyObject {
    }

    public static void main(String[] argv) throws IOException {
        try (ZipFile zipFile = new ZipFile("test")) {
            Map<String, MyObject> result = zipFile.stream()
                    .map(ZipEntry::getName)
                    .collect(Collectors.toMap(f -> "test", f -> new MyObject()));
        }
    }
}

This code builds as-is, however it doesn't build if you just comment the .map(ZipEntry::getName) line. As if the toMap collector could work if the input is a stream of String but not if the input is a stream of ZipEntry?

For reference, here is the beginning of the build error, it's quite obscure:

no suitable method found for collect(Collector<Object,CAP#1,Map<String,MyObject>>)
    method Stream.<R#1>collect(Supplier<R#1>,BiConsumer<R#1,? super CAP#2>,BiConsumer<R#1,R#1>) is not applicable
      (cannot infer type-variable(s) R#1
        (actual and formal argument lists differ in length))
    method Stream.<R#2,A>collect(Collector<? super CAP#2,A,R#2>) is not applicable
      (cannot infer type-variable(s) R#2,A,CAP#3,T#2,K,U
        (argument mismatch; Collector<CAP#2,CAP#4,Map<Object,Object>> cannot be converted to Collector<? super CAP#2,CAP#4,Map<Object,Object>>))
  where R#1,T#1,R#2,A,T#2,K,U are type-variables:
    R#1 extends Object declared in method <R#1>collect(Supplier<R#1>,BiConsumer<R#1,? super T#1>,BiConsumer<R#1,R#1>)
    T#1 extends Object declared in interface Stream
    R#2 extends Object declared in method <R#2,A>collect(Collector<? super T#1,A,R#2>)
    A extends Object declared in method <R#2,A>collect(Collector<? super T#1,A,R#2>)
    T#2 extends Object declared in method <T#2,K,U>toMap(Function<? super T#2,? extends K>,Function<? super T#2,? extends U>)
    K extends Object declared in method <T#2,K,U>toMap(Function<? super T#2,? extends K>,Function<? super T#2,? extends U>)
    U extends Object declared in method <T#2,K,U>toMap(Function<? super T#2,? extends K>,Function<? super T#2,? extends U...
like image 238
Emmanuel Touzery Avatar asked Mar 19 '23 08:03

Emmanuel Touzery


1 Answers

The problem seems to be due to the fact that the stream type uses wild cards - not sure if this is expected behaviour. A workaround would be:

zipFile.stream().map(ZipEntry.class::cast) //or .map(z -> (ZipEntry) z)
like image 171
assylias Avatar answered Apr 01 '23 12:04

assylias