Created
February 21, 2019 09:35
-
-
Save jbarop/4dbbf77e247ba235a6903e56a2ae123c to your computer and use it in GitHub Desktop.
filtering collector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.company; | |
| import java.util.HashSet; | |
| import java.util.Set; | |
| import java.util.function.BiConsumer; | |
| import java.util.function.BinaryOperator; | |
| import java.util.function.Function; | |
| import java.util.function.Supplier; | |
| import java.util.stream.Collector; | |
| public class Main { | |
| static class Person { | |
| final int id; | |
| final String name; | |
| Person(int id, String name) { | |
| this.id = id; | |
| this.name = name; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Person{" + | |
| "id=" + id + | |
| ", name='" + name + '\'' + | |
| '}'; | |
| } | |
| } | |
| static void save(Person person) { | |
| if (person.name == null) { | |
| throw new NullPointerException("name is null"); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| Set<Person> input = new HashSet<>(); | |
| input.add(new Person(1, "1")); | |
| input.add(new Person(2, null)); | |
| input.add(new Person(3, "3")); | |
| Set<Person> outout = input.stream().collect(new Collector<Person, Set<Person>, Set<Person>>() { | |
| @Override | |
| public Supplier<Set<Person>> supplier() { | |
| return HashSet::new; | |
| } | |
| @Override | |
| public BiConsumer<Set<Person>, Person> accumulator() { | |
| return (people, person) -> { | |
| try { | |
| save(person); | |
| people.add(person); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| }; | |
| } | |
| @Override | |
| public BinaryOperator<Set<Person>> combiner() { | |
| return (people, people2) -> { | |
| people.addAll(people2); | |
| return people; | |
| }; | |
| } | |
| @Override | |
| public Function<Set<Person>, Set<Person>> finisher() { | |
| return people -> people; | |
| } | |
| @Override | |
| public Set<Characteristics> characteristics() { | |
| HashSet<Characteristics> characteristics = new HashSet<>(); | |
| characteristics.add(Characteristics.IDENTITY_FINISH); | |
| return characteristics; | |
| } | |
| }); | |
| System.out.println(String.format("inout: %s", input)); | |
| System.out.println(String.format("output: %s", input)); | |
| input.removeAll(outout); | |
| System.out.println(String.format("invalid: %s", input)); | |
| } | |
| } |
Author
jbarop
commented
Feb 21, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment