www.zhblog.net

Java 8 In Action 代码示例(三)

说明

内容来自《Java 8 In Action》


示例一

Optional可以像流一样优雅处理对象,无需考虑对象是否为空。

public class Insurance {

    private String name;

    public String getName() {
        return name;
    }
}


import java.util.Optional;

public class Car {

    private Insurance insurance;

    private Optional<Insurance> optionalInsurance;

    public Insurance getInsurance() {
        return insurance;
    }

    public Optional<Insurance> getOptionalInsurance() {
        return optionalInsurance;
    }
}


import java.util.Optional;

public class Person {

    private Car car;

    private Optional<Car> optionalCar;

    public Car getCar() {
        return car;
    }

    public Optional<Car> getOptionalCar() {
        return optionalCar;
    }
}


import java.util.Optional;

public class PersonMain {

    private final static String UN_KNOWN = "UNKNOWN";

    private String s;

    public static void main(String[] args) {
        // NullPointerException
        // new PersonMain().getCarInsuranceName(new Person());
        String name = new PersonMain().optionalGetCarInsuranceName(Optional.empty());
        System.out.println(name);
        String s = new PersonMain().commonUsage(Optional.empty());
        System.out.println(s);
        System.out.println(new PersonMain().testString());
    }

    public String getCarInsuranceName(Person person) {
        return person.getCar().getInsurance().getName();
    }

    public String optionalGetCarInsuranceName(Optional<Person> optionalPerson) {
        return optionalPerson.flatMap(Person::getOptionalCar)
                .flatMap(Car::getOptionalInsurance)
                .map(Insurance::getName)
                .orElse(UN_KNOWN);
    }

    public String commonUsage(Optional<Person> optionalPerson) {
        return optionalPerson.map(person -> person.getCar())
                .map(car -> car.getInsurance())
                .map(insurance -> insurance.getName())
                .orElse(UN_KNOWN);
    }

    public String testString() {
        Optional<String> optional = Optional.ofNullable(s);
        return optional.orElse(UN_KNOWN);
    }
}


示例二

传统策略模式与lambda

public interface ValidationStrategy {

    boolean execute(String s);
}


public class IsAllLowerCase implements ValidationStrategy {

    @Override
    public boolean execute(String s) {
        return s.matches("[a-z]+");
    }
}


public class IsNumeric implements ValidationStrategy {

    @Override
    public boolean execute(String s) {
        return s.matches("\\d+");
    }
}


public class ValidatorMain {

    public static void main(String[] args) {
        commonValidator();
        lambdaValidator();
    }

    private static void commonValidator() {
        Validator numericValidator = new Validator(new IsNumeric());
        boolean b1 = numericValidator.validate("aaa");
        Validator lowerCaseValidator = new Validator(new IsAllLowerCase());
        boolean b2 = lowerCaseValidator.validate("bbb");

        System.out.println(b1 + " - " + b2);
    }

    private static void lambdaValidator() {
        Validator numericValidator = new Validator((s) -> s.matches("\\d+"));
        boolean b1 = numericValidator.validate("aaa");
        Validator lowerCaseValidator = new Validator((s) -> s.matches("[a-z]+"));
        boolean b2 = lowerCaseValidator.validate("bbb");

        System.out.println(b1 + " - " + b2);
    }
}


示例三

andThen组合任务,上一项任务的结果作为下个任务的输入。

public class Letter {

    public static String addHeader(String text) {
        return "From Raoul, Mario and Alan: " + text;
    }

    public static String addFooter(String text) {
        return text + " Kind regards";
    }

    public static String checkSpelling(String text) {
        return text.replaceAll("labda", "lambda");
    }
}


import java.util.function.Function;

public class LetterMain {

    public static void main(String[] args) {
        Function<String, String> addHeader = Letter::addHeader;
        Function<String, String> addFooter = Letter::addFooter;
        Function<String, String> checkSpelling = Letter::checkSpelling;
        Function<String, String> pipeline = addHeader.andThen(addFooter).andThen(checkSpelling);
        String letter = pipeline.apply("labda is good!");
        System.out.println(letter);
    }
}


示例四

100以内的勾股数

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class NumberMain {

    public static void main(String[] args) {
        even();
        pythagorean();
        pythagorean2();
    }

    private static void even() {
        long count = IntStream.rangeClosed(1, 100)
                .filter(i -> i % 2 == 0)
                .count();
        System.out.println(count);
    }

    private static void pythagorean() {
        IntStream.rangeClosed(1, 100)
                .mapToObj(a -> IntStream.rangeClosed(1, 100)
                        .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                        .mapToObj(b -> new int[]{a, b}))
                .flatMap(s -> s.map(array -> new int[]{array[0], array[1], (int) Math.sqrt(array[0] * array[0] + array[1] * array[1])}))
                .forEach(array -> System.out.println(Arrays.toString(array)));
    }

    private static void pythagorean2() {
        IntStream.rangeClosed(1, 100)
                .boxed()
                .flatMap(a -> IntStream.rangeClosed(a, 100)
                        .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                        .mapToObj(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}))
                .forEach(array -> System.out.println(Arrays.toString(array)));
    }
}


示例五

规约操作

import java.util.Arrays;
import java.util.List;

public class ReduceMain {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        sum(numbers);
        max(numbers);
        min(numbers);
        count(numbers);
    }

    public static void sum(List<Integer> numbers) {
        int sum = numbers.stream()
                .reduce(0, (i, j) -> i + j);
        System.out.println(sum);
    }

    public static void max(List<Integer> numbers) {
        numbers.stream()
                .reduce((i, j) -> i > j ? i : j)
                .ifPresent(System.out::println);
    }

    public static void min(List<Integer> numbers) {
        numbers.stream()
                .reduce(Integer::min)
                .ifPresent(System.out::println);
    }

    public static void count(List<Integer> numbers) {
        int count = numbers.stream()
                .map(n -> 1)
                .reduce(0, (i, j) -> i + j);
        System.out.println(count);
    }
}



  

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情