Last active
July 31, 2018 18:52
-
-
Save shelajev/d38a65f9f161fcb6a734 to your computer and use it in GitHub Desktop.
Java 8 Cheat Sheet Code Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Default methods in interfaces | |
@FunctionalInterface | |
interface Utilities { | |
default Consumer<Runnable> m() { | |
return (r) -> r.run(); | |
} | |
// default methods, still functional | |
Object function(Object o); | |
} | |
class A implements Utilities { // implement | |
public Object function(Object o) { | |
return new Object(); | |
} | |
{ | |
// call a default method | |
Consumer<Runnable> n = new A().m(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// takes an Long, returns a String | |
Function<Long, String> f = (l) -> l.toString(); | |
// takes nothing gives you Threads | |
Supplier<Thread> s = Thread::currentThread; | |
// takes a string as the parameter | |
Consumer<String> c = System.out::println; | |
// use them in with streams | |
new ArrayList<String>().stream(). | |
// peek: debug streams without changes | |
peek(e -> System.out.println(e)). | |
// map: convert every element into something | |
map(e -> e.hashCode()). | |
// filter: pass some elements through | |
filter(e -> ((e.hashCode() % 2) == 0)). | |
// collect the stream into a collection | |
collect(Collectors.toCollection(TreeSet::new)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create an optional | |
Optional<String> optional = Optional.ofNullable(a); | |
// process the optional | |
optional.map(s -> "RebelLabs:" + s); | |
// map a function that returns Optional | |
optional.flatMap(s -> Optional.ofNullable(s)); | |
// run if the value is there | |
optional.ifPresent(System.out::println); | |
// get the value or throw an exception | |
optional.get(); | |
// return the value or the default value | |
optional.orElse("Hello world!"); | |
// return empty Optional if not satisfied | |
optional.filter(s -> s.startsWith("RebelLabs")); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment