Latest — Jun 20, 2014 Java 8 Cheatsheet Syntax for lambda expressions, method references and default methods in Java 8...
Summary statistics on a Java 8 stream of numbers Java 8 streams provide an easy way to calculate basic statistics on the values of a stream of numbers. We can use the summaryStatistics method to get the basic statistics: minimum, maximum, count, sum and average. List numbers = Arrays.asList(10, 3, 2, 5, 9, 4); IntSummaryStatistics stats = numbers.
Distinct elements in Java 8 streams Finding the distinct elements of a Java stream is easy. We can use the distinct method: List words = Arrays.asList("hello", "Java8", "world!", "hello); List distinctWords = words.stream() .distinct() .collect(Collectors.toList()); // ["hello", "Java8", "world!"] The first part of the code example filters the non-empty strings and counts
Java 8 stream map Let's map a list of words using Java 8 streams: List words = Arrays.asList("A", "bbb", "CC", "dd"); // Map the words to UPPERCASE and join them with the ":" separator String joined = words.stream() .map(String::toUpperCase) .collect(Collectors.joining(":")); // "A:BBB:CC:DD" Calling the map method of a
Filter Java 8 stream Let's filter a list of strings using Java 8 streams: List list = Arrays.asList("a", "", "b", "", "c"); // Count the non-empty strings long nonEmptyCount = list.stream() .filter(x -> !x.isEmpty()) .count(); // 3 // Count the empty strings long emptyCount = list.stream() .filter(String::isEmpty) // same as .filter(x -> x.
Java 8 - effectively final variables Effectively final variable is a variable that has not been explicitly marked as final, but it doesn't change its value (basically, an implicit constant). Effectively final variables can be referenced in lambdas, without the need to explicitly mark them as "final": // s is effectively final (not changed anywhere) String s
Java 8 default methods Starting from Java 8, a method which is defined in an interface can have a default implementation: For example: interface Descriptive { default String desc() { return "fantastic"; } } class Item implements Descriptive { // the method "desc" is not implemented here } Item item = new Item(); item.desc(); // "fantastic" class Book implements Descriptive { @Override public
Sort a collection with lambda comparator With Java 8 we can use a lambda expression to implement a Comparator for sorting a collection: class Person { public String name; public int age; } // TODO we should add some persons to this list List persons = new ArrayList<>(); // Using a lambda expression to implement the Comparator Collections.sort(persons,
Java 8 Lambda expressions Let's create and run some Runnable! With Java 8, instead of using anonymous classes, we can use lambda expressions. The syntax (params) -> statement can be used to create an instance of Runnable by implementing its run method. This is possible only for interfaces that have only one abstract method,