Java - What is New in Java 8

Updated: 2018-11-30


double [] d = new double[]{8, 7, -6, 5, -4};
d = -> x > 0).toArray();
//d => [8, 7, 5]

List<User> users = ...
List<User> olderUsers = -> u.age > 30).collect(Collectors.toList());


Stream<String> names = Stream.of("aBc", "d", "ef");
System.out.println( ->  s.toUpperCase()).collect(Collectors.toList()));

new Date Time API

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
LocalDate date = LocalDate.parse("02APR2015", formatter);

Assert.assertEquals(date.getMonth(), Month.APRIL);


Print all the lines:


Pattern matching:

Pattern.compile(" ").splitAsStream("a b c").forEach(System.out::println);

Generate random integers

new Random().ints().limit(5).forEach(System.out::println);

Print sorted chars

"hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch));

Word count
    .flatMap(line -> Stream.of(line.split("\\W+")))
    .collect(Collectors.groupingBy(String::toLowerCase, Collectors.summingInt(s -> 1)));

Java 7 vs Java 8: HashMap

HashMap collision: if two entries have the same key, they will be saved internally as follows

  • Java 7: use LinkedList, will be slow if there are too many collisions
  • Java 8: use red-black tree

Using Java 8 HashMaps buckets with too

Suppose we have a Person class defined and may have the following operations:

Map<Person, String> map = new HashMap<>();
map.put(person, “value");

In Java 8:

  • If there are too many entries under the same bucket, it will be tree-fied once a threshold value is met.
  • If Person is comparable, it will be much faster.
public int compareTo(Person person) {