Skip to content

Instantly share code, notes, and snippets.

@sffej
Forked from shelajev/Debuggable.java
Created December 30, 2021 01:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sffej/85f0b37c1861a4d85deb32f42d0859ed to your computer and use it in GitHub Desktop.
Save sffej/85f0b37c1861a4d85deb32f42d0859ed to your computer and use it in GitHub Desktop.
Java 8 cheat sheet code
public interface Debuggable {
default String debug() {
StringBuilder sb = new StringBuilder(this.getClass().getName());
sb.append(" [ ");
Field[] fields = this.getClass().getDeclaredFields();
for(Field f: fields) {
f.setAccessible(true);
try {
sb.append(f.getName() + " = " + f.get(this));
sb.append(", ");
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
sb.append("]");
return sb.toString();
}
}
// takes a 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))
public class Main implements Debuggable {
int a = 100;
String b = "Home";
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.debug());
}
}
User user = getUser(name); // might return null
Location location = null;
if(user != null) {
location = getLocation(user);
}
Optional<User> user = Optional.ofNullable(getUser(user));
Optional<Location> location = user.map(u -> getLocation(user));
public <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment