• Home
  • About
    • Ahmed DAMMAK photo

      Ahmed DAMMAK

      Full Stack Developer

    • Learn More
    • Twitter
    • LinkedIn
    • Github
  • All Posts
  • All Tags
  • Projects

What's new in Java 9 ?

31 Oct 2020

Reading time ~2 minutes

This post aims to resume java 9 news. See github

Exercice

Let’s take the following class

import lombok.Builder;
import lombok.Getter;

import java.util.List;
import java.util.Map;

public class Exercise1 {

    @Builder
    @Getter
    static class Family {
        private String name ;
        private List<String> firstNames ;
    }

    Map<String,List<String>> getMembersBySameName(List<Family> families) {
        return Map.of() ;
    }
    
}

and the expected test

import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

class Exercise1ShouldTest {

    @Test
    void get_members_by_family_name() {
        var family1 = Exercise1.Family.builder().name("Name1").firstNames(List.of("A","B","C")).build() ;
        var family2 = Exercise1.Family.builder().name("Name2").firstNames(List.of("D","E")).build() ;
        var family3 = Exercise1.Family.builder().name("Name1").firstNames(List.of("F","G")).build() ;
        var result = new Exercise1().getMembersBySameName(List.of(family1,family2,family3)) ;
        assertThat(result).containsExactly(
                entry("Name1",List.of("A","B","C","F","G")),
                entry("Name2",List.of("D","E"))) ;
    }

}

Solution

The solution is to use Collectors.flatMapping

    Map<String,List<String>> getMembersBySameName(List<Family> families) {
        return families.stream().
                collect(
                  Collectors.groupingBy(Family::getName,
                  Collectors.flatMapping(family -> family.getFirstNames().stream(),Collectors.toList())));
    }

Stream Ofnullable

Given a collection with null elements. The Stream.ofNullable can filter null emements

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.ofNullable;

public class StreamOfNullable {

    public static void main(String[] args) {
        var dictionary = Map.of("1","1","2","2") ;
        var elements = List.of("1" , "2","3") ;
        var nonNullValue = elements.stream()
                .map(dictionary::get)
                .filter(Objects::nonNull)
                .collect(toList()) ;
        var nonNullValue2 = elements.stream().
                flatMap(s -> ofNullable(dictionary.get(s)))
                .collect(toList());
        System.out.println(nonNullValue);
        System.out.println(nonNullValue2);
    }
}

This code prints

[1, 2]
[1, 2]

Private interface method

Since Java 9, it’s possible to add private method in interface.

Improved try-with-resources

Sample 1 :

Reader inputString = new StringReader(message);
  BufferedReader br = new BufferedReader(inputString);
  try (br) {
      return br.readLine();
  }
}

Sample 2 :

 BufferedReader reader1 = new BufferedReader(new FileReader("file.txt"));
 try (reader1) {
   System.out.println(reader1.readLine());
 }

Sample 3 :

Resource res1 = new Resource("res1");
final Resource res2 = new Resource("res2");
try(res1;res2){
        //Code using resource objects
}

TakeWhile(Predicate Interface) & Predicate.not

public class TakeWhile {
    
    public static void main(String[] args) {
        Stream.of("a","b","").takeWhile(Predicate.not(String::isEmpty)).forEach(System.out::print);
    }
}

This code will prints ab

Optional

Optional Class was introduced in Java 8 to avoid null checks and NullPointerException issues. In java 9, three new methods are added to improve its functionality.

  • stream()
  • ifPresentOrElse()
  • or()


Java9