代码示例

package com.carl;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.util.stream.Collectors.joining;

public class CollectionsTest {

    public static Predicate<String> checkSize(final int size) {
        return s -> s.length() > size;
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "ac");
        List<String> personList = Arrays.asList("p01", "p02", "p03");

        list.forEach(new Consumer<Object>() {
            @Override
            public void accept(Object t) {
                System.out.println(t);
            }
        });

        System.out.println("----");

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

        System.out.println("----");

        list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
        list.stream().map(String::toUpperCase).forEach(System.out::println);

        System.out.println("----");

        list.stream().map(s -> s.length()).forEach(System.out::println);

        System.out.println("----");

        list.stream().filter(s -> s.length()>1).forEach(System.out::println);

        System.out.println("----");

        final Predicate<String> filterPolicy = s -> s.length() > 1;
        list.stream().filter(filterPolicy).forEach(System.out :: println);
        personList.stream().filter(filterPolicy).forEach(System.out :: println);

        System.out.println("----");

        System.out.println(list.stream().filter(filterPolicy).count());

        System.out.println("----");

        personList.stream().filter(checkSize(2)).forEach(System.out :: println);

        System.out.println("----");

//      final Function<Integer, Predicate<String>> checkSizeFun = (Integer size) -> {
//          Predicate<String> checkSize = (String s) -> s.length() > size;
//          return checkSize;
//      };

        final Function<Integer, Predicate<String>> checkSizeFun = size -> s -> s.length() > size;

        personList.stream().filter(checkSizeFun.apply(2)).forEach(System.out :: println);

        System.out.println("----");

        Optional<String> firstResult = personList.stream().filter(checkSizeFun.apply(3)).findFirst();
        System.out.println(firstResult.orElse("No found"));

        firstResult = personList.stream().filter(checkSizeFun.apply(2)).findFirst();
        firstResult.ifPresent(s -> System.out.println(s + " is found"));

        System.out.println("----");

        System.out.println("Total size:" + personList.stream().mapToInt(s -> s.length()).sum());

        System.out.println("----");

        //final Optional<String> findOneByReduce = personList.stream().reduce((s1, s2) -> s1.length() >= s2.length() ? s1 : s2);
        final Optional<String> findOneByReduce = personList.stream().reduce((s1, s2) -> {
            System.out.print("s1:" + s1);
            System.out.println(", s2:" + s2);
            return s1.length() >= s2.length() ? s1 : s2;
        });
        findOneByReduce.ifPresent(s -> System.out.println(s));

        System.out.println("----");

        //final String optionalReduce = personList.stream().reduce("p0", (s1, s2) -> s1.length() >= s2.length() ? s1 : s2);
        final String optionalReduce = personList.stream().reduce("p0", (s1, s2) -> {
            System.out.print("s1:" + s1);
            System.out.println(", s2:" + s2);
            return s1.length() >= s2.length() ? s1 : s2;
        });
        System.out.println(optionalReduce);

//      String reduceResult = "p0";
//      for (String s : personList) {
//          System.out.println(reduceResult.length() >= s.length());
//      }

        System.out.println("----");
        System.out.println(String.join(",", list));

        System.out.println("----");
        System.out.println(list.stream().map(String::toUpperCase).collect(joining(",")));       
    }
}

package com.carl;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.reducing;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
import static java.util.Comparator.comparing;

import com.carl.beans.Person;

public class StringsComparatorsFilters {

    private static void printC(int c) {
        System.out.println((char)c);
    }

    public static void main(String[] args) {
        final String str = "wa68";

        str.chars().forEach(c -> System.out.println(c));

        System.out.println("---------------");

        str.chars().forEach(System.out::println);

        System.out.println("---------------");

        str.chars().forEach(StringsComparatorsFilters::printC);

        System.out.println("---------------");

        str.chars().mapToObj(c -> Character.valueOf((char)c)).forEach(System.out::println);

        System.out.println("---------------");

        str.chars().filter(c -> Character.isDigit(c)).forEach(c -> printC(c));
        str.chars().filter(Character::isDigit).forEach(StringsComparatorsFilters::printC);

        System.out.println("---------------");

        final List<Person> people = Arrays.asList(
                new Person("jx", 24),
                new Person("hh", 21),
                new Person("jj", 24),
                new Person("ss", 28));
//      people.add(new Person("wu", 27)); //java.lang.UnsupportedOperationException
//  asList 的返回对象是一个 Arrays 内部类,并没有实现集合的修改方法。 Arrays . asList体现的是适配器模式,只是转换接口,后台的数据仍是数组

        people.stream().sorted((p1, p2) -> p1.ageDiff(p2)).forEach(System.out::println);

        System.out.println("---------------");

        people.stream().sorted(Person::ageDiff).forEach(System.out::println);

        System.out.println("---------------");

        Comparator<Person> compareAscending = (p1, p2) -> p1.ageDiff(p2);
        Comparator<Person> compareDscending = compareAscending.reversed();

        people.stream().sorted(compareDscending).forEach(System.out::println);

        System.out.println("---------------");

        people.stream().sorted((p1, p2) -> p1.getName().compareToIgnoreCase(p2.getName())).forEach(System.out::println);

        System.out.println("---------------");

        people.stream().min(Person::ageDiff).ifPresent(youngest -> System.out.println("Youngest:" + youngest));
        people.stream().max(Person::ageDiff).ifPresent(eldest -> System.out.println("Eldest:" + eldest));

        System.out.println("---------------");

        final Function<Person, String> byName = p -> p.getName();
        people.stream().sorted(comparing(byName)).forEach(System.out::println);

        System.out.println("---------------");

        final Function<Person, Integer> byAge = p -> p.getAge();
        people.stream().sorted(comparing(byAge)).forEach(System.out::println);

        System.out.println("---------------");

        people.stream().sorted(comparing(byAge).thenComparing(byName)).forEach(System.out::println);

        System.out.println("---------------");

        List<Person> oldThan25 = people.stream().filter(p -> p.getAge() > 25).collect(Collectors.toList());
        oldThan25.forEach(System.out::println);

        System.out.println("---------------");

        Map<Integer, List<Person>> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
        System.out.println(peopleByAge);

        System.out.println("---------------");

        Map<Integer, List<String>> nameOfPeopleByAge = people.stream().collect(groupingBy(Person::getAge, mapping(Person::getName, toList())));
        System.out.println(nameOfPeopleByAge);

        System.out.println("---------------");

        Map<Integer, Long> coutPeopleByAge = people.stream().collect(groupingBy(Person::getAge, counting()));
        System.out.println(coutPeopleByAge);

        System.out.println("---------------");

        Comparator<Person> compareByAge = Comparator.comparing(Person::getAge);
        Map<Character, Optional<Person>> oldestPersonOfEachLetter = people.stream().collect(groupingBy(p -> p.getName().charAt(0),
                reducing(BinaryOperator.maxBy(compareByAge))));

        System.out.println(oldestPersonOfEachLetter);
    }
}

我的理解

就是新的 API 学习了,然后好多对集合的操作

参考

《Functional.Programming.in.Java》


↙↙↙阅读原文可查看相关链接,并与作者交流