Skip to content

Instantly share code, notes, and snippets.

@shelajev
Last active February 23, 2022 05:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save shelajev/c58afed75aea3387fcac to your computer and use it in GitHub Desktop.
Save shelajev/c58afed75aea3387fcac 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)
@elecay
Copy link

elecay commented Dec 9, 2015

On line Lambdas1.java, line 1 I think should be:

// takes a Long, return a String

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