I got a weird exception while experimenting with Java8 & Guava.
This works:
private static Set<Character> uniqueChars(String s) {
Set<Character> set= new HashSet<>();
s.chars().mapToObj(i -> (char) i).forEach(set::add);
return set;
}
But this one gives NoSuchMethodError
private static Multiset<Character> allChars(String s) {
HashMultiset<Character> set = HashMultiset.create();
s.chars().mapToObj(i -> (char) i).forEach(set::add);
return set;
}
at:
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.HashMultiset.add(Ljava/lang/Character;)Z
at java.lang.invoke.MethodHandleNatives.resolve(Native Method)
at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:965)
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:990)
at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1387)
at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(MethodHandles.java:1739)
at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:442)
at net.gencsoy.TestJava8.allChars(TestJava8.java:14)
at net.gencsoy.TestJava8.main(TestJava8.java:31)
I would have guessed Java should be oblivious to the collection type but apparently it is not the case.
This one also works, where the Lambda expression converted to more explicit representation. I thought it was just a syntetic sugar, handled during compile time:
private static Multiset<Character> allChars(String s) {
HashMultiset<Character> set = HashMultiset.create();
s.chars().mapToObj(i -> (char) i).forEach((Character c) -> set.add(c));
return set;
}
I am using JDK8_u20, Guava 18.0, Eclipse 4.4.0
This might not be directly relevant to Guava, but I’m eager to learn the root cause of the problem. Seeing reflection related methods in the call stack of the exception made me suspicious about Java8 features’ performance.