Skip to content

Instantly share code, notes, and snippets.

@blouerat
Last active September 29, 2016 00:50
Show Gist options
  • Save blouerat/53bbcf2d253c21053107 to your computer and use it in GitHub Desktop.
Save blouerat/53bbcf2d253c21053107 to your computer and use it in GitHub Desktop.
Why Java 8 matters
package java8fun;
public class Foobar {
private String foo;
private Integer bar;
public Foobar(String foo, Integer bar) {
this.foo = foo;
this.bar = bar;
}
public String getFoo() {
return foo;
}
public Integer getBar() {
return bar;
}
@Override
public String toString() {
return "Foobar{" +
"foo='" + foo + '\'' +
", bar=" + bar +
'}';
}
}
package java8fun;
import java.util.Comparator;
import java.util.function.Function;
import java.util.stream.Stream;
public class Main {
public static Stream<Foobar> foobars() {
return Stream.of(new Foobar("foo!!", 42), new Foobar("bar!!!", 10), new Foobar("zor", 23));
}
public static <A, B, C> Function<A, C> compose(Function<B, C> f, Function<A, B> g) {
return f.compose(g);
}
public static void main(String[] args) {
/*
Alphabetically sorting the stream according to the foo parameter, no problem so far.
*/
foobars().sorted(Comparator.comparing(Foobar::getFoo)).forEach(System.out::println);
/*
Sorting the stream according to the length of the foo string, types are perfectly inferred, no problem either.
*/
foobars().sorted(Comparator.comparing(fb -> fb.getFoo().length())).forEach(System.out::println);
/* Let's just call reverse on the comparator to get the longest strings first, should be easy, right?
NOPE! Can't infer Foobar anymore!
Error:(35, 55) java: cannot find symbol
symbol: method getFoo()
location: variable fb of type java.lang.Object
*/
foobars().sorted(Comparator.comparing(fb -> fb.getFoo().length()).reversed()).forEach(System.out::println);
/*
Hmm, that sucks man, but the young 22 yo naive me still has hope.
We're functional java programmers now, let's try and compose functions!
I've heard about java.util.Function#compose…
NOPE! I can't haz composition :(
Error:(45, 48) java: method reference not expected here
*/
foobars().sorted(Comparator.comparing((String::length).compose(Foobar::getFoo)).reversed()).forEach(System.out::println);
/*
Turns out you can't directly call a method on a method reference :(
The only workaround I found was to redefine compose.
So yeah, that's it, Java's incredible type inference!
*/
foobars().sorted(Comparator.comparing(compose(String::length, Foobar::getFoo)).reversed()).forEach(System.out::println);
}
}
@Quar
Copy link

Quar commented Sep 29, 2016

Got same problem "method reference not expected here" when attempting to make fun of (MyClasss::new).apply(), find by Google, fond of the story :D

Hmm, that sucks man, but the young 22 yo naive me still has hope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment