Cheatography
https://cheatography.com
Lambdas, Stream API, Optional and Date/Time
This is a draft cheat sheet. It is a work in progress and is not finished yet.
Lambdas
|
Package |
|
Optional. Force a compiler error if the interface has more than one abstract method. |
(String text) -> System.out.println(text)
(text) -> System.out.println(text)
System.out::println
|
Anonymous function. |
Default/static method in interface |
Stream API - Generatoren
Iterate / Range |
Automatische Erzeugung von IntStream durch Iteration |
Builder |
Aufbau eines Streams mit Elementen ohne Collection |
Of |
Sammlung ovn Objekten als Argument |
Generate |
Supplier Lambda zur Generierung von Einträgen |
Files (NIO), ZipFile, JarFile, Patterns (RegEx) |
Stream API - Transformation
map( lambda ) |
Objekte von Eingabetyp in Ausgabetyp umwandeln |
flatMap( lambda ) |
Collection-Elemente in Stream-Elemente begradigen (Array[][] -> Array[]) |
Stream API - Combining / Shortening
.filter( p -> p.name.startsWith("M") ) |
.reduce( (x1, x2) -> x1+ x2) |
y = ((x1 + x2) + x3) + ... |
.collect(Collectors.joining(", ")); |
e1 + ", " + e2 + ... |
.limit(5) |
limit number of results |
.skip(5) |
skip elements |
Stream API - Aggregation
Those APIs consider the whole set |
.sorted() |
.min()/.max() |
.groupingBy( |
Gruppieren gleicher Elemente |
.distinct() |
make list unique based on lambda |
.count() |
Stream API - Ergebnisse
forEach / forEachOrdered |
toArray(String[]::new) |
collect(Collectors.toList()); |
collect(Collectors.toCollection(ArrayList::new)); |
|
|
Stream API
List<Person> persons1, persons2;
Stream.of(persons1, persons2) // stream of lists
.flatMap(ps -> ps.stream()) // stream of obj
.map(p -> p.firstName + " " + p.name) // stream of name
.forEach(System.out::println);
IntStream.iterate(0, i -> i + 1)
.limit(10)
.forEach(System.out::print);
Stream.builder()
.add("Wir ").add("bauen ").add("einen Satz.").build()
.forEachOrdered(...);
Stream.generate(() -> Double.valueOf(Math.random() * 100).intValue())
.limit(5).forEach(...)
|
Java I/O, NIO
Files.lines(Paths.get(this.class.getResource("file.txt").toURI()))
.count();
|
Date/Time API
LocalTime |
LocalDate |
LocalDateTime |
ZonedDateTime.of() / .now(ZoneId.of("CET")); |
Instant |
Maschinenzeit, genauer, ohne Zeitzone |
TemporalAdjuster |
Duration |
DateTimeFormatter.ISO_OFFSET_DATE_TIME // 2011-12-03T10:15:30+01:00 |
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG) // June 20, 2014; 10:15:58 GMT+1 |
Optional
Optional<String> result = doSomething(); if ( result.isPresent()) result.get(); |
String result = doSomething().orElse("unknown"); |
doSomething().ifPresent(lambda); |
Repeatable Annotation
@Repeatable(TableAnnos.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface TableAnnos {
Table[] value();
}
@Table("Customer")
@Table("Employee")
public class Person {
}
|
|