Java - What is New in Java 8

Updated: 2018-11-30

Lambda

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

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

Stream

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

new Date Time API

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

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

One-liner

Print all the lines:

Files.lines(Paths.get("./data.txt")).forEach(System.out::println);

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

lines.stream()
    .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");
map.get(person);

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.
@Override
public int compareTo(Person person) {
    return this.id.compareTo(person.id);
}