Skip to content

Instantly share code, notes, and snippets.

@jbarop
Created February 21, 2019 09:35
Show Gist options
  • Select an option

  • Save jbarop/4dbbf77e247ba235a6903e56a2ae123c to your computer and use it in GitHub Desktop.

Select an option

Save jbarop/4dbbf77e247ba235a6903e56a2ae123c to your computer and use it in GitHub Desktop.
filtering collector
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));
}
}
@jbarop
Copy link
Author

jbarop commented Feb 21, 2019

inout: [Person{id=2, name='null'}, Person{id=1, name='1'}, Person{id=3, name='3'}]
output: [Person{id=2, name='null'}, Person{id=1, name='1'}, Person{id=3, name='3'}]
invalid: [Person{id=2, name='null'}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment