comparator 比較器複合java
//排序 Comparator.comparing(Apple::getWeight); List<Apple> list = Stream.of(new Apple(1, "a"), new Apple(2, "b"), new Apple(3, "c")) .collect(Collectors.toList()); list.sort(Comparator.comparing(Apple::getWeight)); //按重量排序 list.stream() .sorted(Comparator.comparing(Apple::getName)) .collect(Collectors.toList()); //先按重量倒序,若是重量同樣,再按名稱排序 list.sort(Comparator.comparing(Apple::getWeight) .reversed() .thenComparing(Apple::getName));
Predicate 謂詞 複合app
//判斷是蘋果b Predicate<Apple> isBApple = apple -> Objects.equals("b", apple.getName()); isBApple.negate(); //不是蘋果b //不是蘋果b,而且蘋果重量大於1 --> apple.name != "b" && apple.weight > 1 isBApple.negate().and(apple -> apple.getWeight() > 1); // ((apple.name != "b") && apple.weight > 1) or apple.weight==0 isBApple.negate() .and(apple -> apple.getWeight() > 1) .or(apple -> apple.getWeight()==0);
Function 函數複合函數
//f(x) = x+1 Function<Integer, Integer> f = x -> x + 1; //g(x) = x*2 Function<Integer, Integer> g = x -> x * 2; // g(f(x)) Function<Integer, Integer> h = f.andThen(g); // f(g(x)) Function<Integer, Integer> z = f.compose(g);