Java 7 / 8 / 9

try-with-resources

        try {
            PrintWriter writer = new PrintWriter("out.txt");
            writer.println("Hello");
            writer.println("World!");
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        PrintWriter writer = null;
        try {
            writer = new PrintWriter("out.txt");
            writer.println("Hello");
            writer.println("World!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }


        try (PrintWriter writer = new PrintWriter("out.txt")) {
            writer.println("Hello");
            writer.println("World!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

Java 7

java.nio.file.*

ny i Java 7

forbedret i Java 8

List<String> lines = Files.readAllLines(Paths.get("JavaNio.java"));
// do something
Files.write(Paths.get("out.txt"), lines);

...

nytt i Java 7

int i = 1_000_000;

int b = 0b110;

Implementering av metoder i grensesnitt

nytt i Java 8

Før Java 8 kunne grensesnitt kun ha abstrakte metoder

public interface Iterator<E> {
    boolean hasNext();

    E next();

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}
public interface Iterator<E> {
    boolean hasNext();

    E next();

    void remove();
}

Nye hjelpemetoder i grensesnitt

nytt i Java 8

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String toString() {
        return name + " " + age;
    }
}
List<Person> persons = new LinkedList<>();
persons.add(new Person("Bob", 19));
persons.add(new Person("Bob", 65));
persons.add(new Person("Arne", 32));
persons.add(new Person("Arne", 10));
persons.add(new Person("Arne", 40));
persons.add(new Person("Kari", 27));
persons.add(new Person("Gunvor", 90));
persons.add(new Person("Kjell", 90));
persons.add(new Person("Bob", 5));
persons.add(new Person("Bob", 15));

nytt i Java 8

persons.sort(
    Comparator
        .comparing(Person::getName)
        .thenComparingInt(Person::getAge));

persons.forEach(System.out::println);

Nye hjelpemetoder i grensesnitt

nytt i Java 8

Map<String,Integer> nameCount = new HashMap<>();
for (Person p : persons) {
    nameCount.compute(p.getName(), (k, v) -> {
        if (v == null) return 1;
        return v + 1;
    });
}

nameCount.forEach((k, v) -> {
    System.out.println(k + " " + v);
});

Nye hjelpemetoder i grensesnitt

Stream<E>

nytt i Java 8

En sekvens av elementer man kan gjøre funksjonelle operasjoner på.

 

Det meste kan behandles som en strøm:

  • Alle collections(List, Set, etc) kan konverteres til en strøm med metoden .stream()
  • Arrays.stream() lager en strøm av en array
  • java.nio.file.Files har diverse metoder for å lage strømmer basert på filer

Stream<E>

nytt i Java 8

List<Person> persons = ...

long nameCount = persons.stream()
        .map(Person::getName)
        .distinct()
        .count();

System.out.println("There are " + nameCount + " different names");

int totalAge = persons.stream()
        .mapToInt(Person::getAge)
        .sum();

System.out.println("The total age is " + totalAge);

map

Stream<E>

nytt i Java 8

List<Person> persons = ...

System.out.println("The following persons are of age:");
persons.stream()
        .filter(p -> p.getAge() >= 18)
        .forEach(p -> {
            System.out.println(" -" + p.getName());
        });

filter

Stream<E>

nytt i Java 8

ArrayList<String> numbers = new ArrayList<>();

new Scanner(new File("input.txt"))
	.useDelimiter("\\D+")
	.forEachRemaining(numbers::add);

int sumOfOddSquares = numbers.stream()
	.mapToInt(Integer::parseInt)
	.filter(x -> x % 2 != 0)
	.map(x -> x * x)
	.sum();

System.out.println(sumOfOddSquares);

Stream<E>

nytt i Java 8

Stream<Path> files = Files.find(
        Paths.get(".."),
        5,
        (path, attr) -> path.toString().endsWith(".java"));

long count = files
        .flatMap(path -> {
            try {
                return Files.lines(path);
            } catch (Exception ignored) {
                return Stream.empty();
            }
        })
        .filter(s -> !s.isEmpty())
        .count();

System.out.println(count);

JShell

nytt i Java 9

# For mac:
export JAVA_HOME=$(/usr/libexec/java_home)


alias jshell="$JAVA_HOME/bin/jshell"

Ikke ennå en av de "eksporterte" programmene

Optional

nytt i Java 8

Optional<Integer> x = ...

Java 7/8/9

By Erik Vesteraas

Java 7/8/9

  • 1,647