Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- List<Person> beerDrinkers = persons.stream()
- .filter(p -> p.getAge() > 16).collect(Collectors.toList());
- persons.removeIf(p -> p.getAge() <= 16);
- List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
- greaterThan(16)));
- public interface IPredicate<T> { boolean apply(T type); }
- public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
- Collection<T> result = new ArrayList<T>();
- for (T element: target) {
- if (predicate.apply(element)) {
- result.add(element);
- }
- }
- return result;
- }
- Predicate<User> isAuthorized = new Predicate<User>() {
- public boolean apply(User user) {
- // binds a boolean method in User to a reference
- return user.isAuthorized();
- }
- };
- // allUsers is a Collection<User>
- Collection<User> authorizedUsers = filter(allUsers, isAuthorized);
- public class Predicate {
- public static Object predicateParams;
- public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
- Collection<T> result = new ArrayList<T>();
- for (T element : target) {
- if (predicate.apply(element)) {
- result.add(element);
- }
- }
- return result;
- }
- public static <T> T select(Collection<T> target, IPredicate<T> predicate) {
- T result = null;
- for (T element : target) {
- if (!predicate.apply(element))
- continue;
- result = element;
- break;
- }
- return result;
- }
- public static <T> T select(Collection<T> target, IPredicate<T> predicate, T defaultValue) {
- T result = defaultValue;
- for (T element : target) {
- if (!predicate.apply(element))
- continue;
- result = element;
- break;
- }
- return result;
- }
- }
- List<MyTypeA> missingObjects = (List<MyTypeA>) Predicate.filter(myCollectionOfA,
- new IPredicate<MyTypeA>() {
- public boolean apply(MyTypeA objectOfA) {
- Predicate.predicateParams = objectOfA.getName();
- return Predicate.select(myCollectionB, new IPredicate<MyTypeB>() {
- public boolean apply(MyTypeB objectOfB) {
- return objectOfB.getName().equals(Predicate.predicateParams.toString());
- }
- }) == null;
- }
- });
- MyType myObject = Predicate.select(collectionOfMyType, new IPredicate<MyType>() {
- public boolean apply(MyType objectOfMyType) {
- return objectOfMyType.isDefault();
- }}, collectionOfMyType.get(0));
- final UserService userService = ... // perhaps injected IoC
- final Optional<UserModel> userOption = userCollection.stream().filter(u -> {
- boolean isAuthorized = userService.isAuthorized(u);
- return isAuthorized;
- }).findFirst();
- final UserService userService = ... // perhaps injected IoC
- final List<UserModel> userOption = userCollection.stream().filter(u -> {
- boolean isAuthorized = userService.isAuthorized(u);
- return isAuthorized;
- }).collect(Collectors.toList());
- Iterator<Foo> it = col.iterator();
- while( it.hasNext() ) {
- Foo foo = it.next();
- if( !condition(foo) ) it.remove();
- }
- CollectionUtils.filterInPlace(col,
- new IPredicate<Foo>(){
- public boolean keepIt(Foo foo) {
- return foo.isBar();
- }
- });
- List<Person> olderThan30 =
- //Create a Stream from the personList
- personList.stream().
- //filter the element to select only those with age >= 30
- filter(p -> p.age >= 30).
- //put those filtered elements into a new List.
- collect(Collectors.toList());
- Collection<T> collection = ...;
- Stream<T> stream = collection.stream().filter(...);
- List<Integer> numbers = Arrays.asList(12, 74, 5, 8, 16);
- numbers.stream().filter(n -> n > 10).forEach(System.out::println);
- Observable.from(Arrays.asList(1, 2, 3, 4, 5))
- .filter(new Func1<Integer, Boolean>() {
- public Boolean call(Integer i) {
- return i % 2 != 0;
- }
- })
- .subscribe(new Action1<Integer>() {
- public void call(Integer i) {
- System.out.println(i);
- }
- });
- 1
- 3
- 5
- public interface Predicate<T> {
- public boolean filter(T t);
- }
- void filterCollection(Collection<T> col, Predicate<T> predicate) {
- for (Iterator i = col.iterator(); i.hasNext();) {
- T obj = i.next();
- if (predicate.filter(obj)) {
- i.remove();
- }
- }
- }
- List<MyObject> myList = ...;
- filterCollection(myList, new Predicate<MyObject>() {
- public boolean filter(MyObject obj) {
- return obj.shouldFilter();
- }
- });
- List<Integer> jdkList = Arrays.asList(1, 2, 3, 4, 5);
- MutableList<Integer> ecList = Lists.mutable.with(1, 2, 3, 4, 5);
- List<Integer> selected = Lists.mutable.with(1, 2);
- List<Integer> rejected = Lists.mutable.with(3, 4, 5);
- Predicate<Integer> lessThan3 = new Predicate<Integer>()
- {
- public boolean accept(Integer each)
- {
- return each < 3;
- }
- };
- Assert.assertEquals(selected, Iterate.select(jdkList, lessThan3));
- Assert.assertEquals(selected, ecList.select(lessThan3));
- Assert.assertEquals(selected, Iterate.select(jdkList, Predicates.lessThan(3)));
- Assert.assertEquals(selected, ecList.select(Predicates.lessThan(3)));
- Assert.assertEquals(
- selected, ecList.selectWith(Predicates2.<Integer>lessThan(), 3));
- Assert.assertEquals(rejected, Iterate.reject(jdkList, lessThan3));
- Assert.assertEquals(rejected, ecList.reject(lessThan3));
- Assert.assertEquals(selected, Iterate.select(jdkList, each -> each < 3));
- Assert.assertEquals(rejected, Iterate.reject(jdkList, each -> each < 3));
- Assert.assertEquals(selected, gscList.select(each -> each < 3));
- Assert.assertEquals(rejected, gscList.reject(each -> each < 3));
- PartitionIterable<Integer> jdkPartitioned = Iterate.partition(jdkList, lessThan3);
- Assert.assertEquals(selected, jdkPartitioned.getSelected());
- Assert.assertEquals(rejected, jdkPartitioned.getRejected());
- PartitionList<Integer> ecPartitioned = gscList.partition(lessThan3);
- Assert.assertEquals(selected, ecPartitioned.getSelected());
- Assert.assertEquals(rejected, ecPartitioned.getRejected());
- import static ch.akuhn.util.query.Query.select;
- import static ch.akuhn.util.query.Query.$result;
- import ch.akuhn.util.query.Select;
- Collection<String> collection = ...
- for (Select<String> each : select(collection)) {
- each.yield = each.value.length() > 3;
- }
- Collection<String> result = $result();
- List<Customer> list ...;
- List<Customer> newList = new ArrayList<>();
- for (Customer c : list){
- if (c.getName().equals("dd")) newList.add(c);
- }
- List<Customer> newList = list.stream().filter(c -> c.getName().equals("dd")).collect(toList());
- LinkedList<Person> list = ......
- LinkedList<Person> filtered =
- Query.from(list).where(Condition.ensure("age", Op.GTE, 21));
- LinkedList<Person> list = ....
- LinkedList<Person> filtered = Query.from(list).where("x => x.age >= 21");
- List<Integer> myList = new ArrayList<Integer>(){ 1, 2, 3, 4, 5 }
- Iterable<Integer> filtered = Iterable.wrap(myList).select(new Predicate1<Integer>()
- {
- public Boolean call(Integer n) throws FunctionalException
- {
- return n % 2 == 0;
- }
- })
- for( int n : filtered )
- {
- System.out.println(n);
- }
- for( int n : myList )
- {
- if( n % 2 == 0 )
- {
- System.out.println(n);
- }
- }
- ArrayList<Item> filtered = new ArrayList<Item>();
- for (Item item : items) if (condition(item)) filtered.add(item);
- Collection<Dto> testList = new ArrayList<>();
- class Dto
- {
- private int id;
- private String text;
- public int getId()
- {
- return id;
- }
- public int getText()
- {
- return text;
- }
- }
- Filter<Dto> query = CQ.<Dto>filter(testList)
- .where()
- .property("id").eq().value(1);
- Collection<Dto> filtered = query.list();
- Filter<Dto> query = CQ.<Dto>filter(testList)
- .where()
- .property(Dto::getId)
- .eq().value(1);
- Collection<Dto> filtered = query.list();
- Filter<Dto> query = CQ.<Dto>filter()
- .from(testList)
- .where()
- .property(Dto::getId).between().value(1).value(2)
- .and()
- .property(Dto::grtText).in().value(new string[]{"a","b"});
- Filter<Dto> query = CQ.<Dto>filter(testList)
- .orderBy()
- .property(Dto::getId)
- .property(Dto::getName)
- Collection<Dto> sorted = query.list();
- GroupQuery<Integer,Dto> query = CQ.<Dto,Dto>query(testList)
- .group()
- .groupBy(Dto::getId)
- Collection<Grouping<Integer,Dto>> grouped = query.list();
- class LeftDto
- {
- private int id;
- private String text;
- public int getId()
- {
- return id;
- }
- public int getText()
- {
- return text;
- }
- }
- class RightDto
- {
- private int id;
- private int leftId;
- private String text;
- public int getId()
- {
- return id;
- }
- public int getLeftId()
- {
- return leftId;
- }
- public int getText()
- {
- return text;
- }
- }
- class JoinedDto
- {
- private int leftId;
- private int rightId;
- private String text;
- public JoinedDto(int leftId,int rightId,String text)
- {
- this.leftId = leftId;
- this.rightId = rightId;
- this.text = text;
- }
- public int getLeftId()
- {
- return leftId;
- }
- public int getRightId()
- {
- return rightId;
- }
- public int getText()
- {
- return text;
- }
- }
- Collection<LeftDto> leftList = new ArrayList<>();
- Collection<RightDto> rightList = new ArrayList<>();
- Collection<JoinedDto> results = CQ.<LeftDto, LeftDto>query().from(leftList)
- .<RightDto, JoinedDto>innerJoin(CQ.<RightDto, RightDto>query().from(rightList))
- .on(LeftFyo::getId, RightDto::getLeftId)
- .transformDirect(selection -> new JoinedDto(selection.getLeft().getText()
- , selection.getLeft().getId()
- , selection.getRight().getId())
- )
- .list();
- Filter<Dto> query = CQ.<Dto>filter()
- .from(testList)
- .where()
- .exec(s -> s.getId() + 1).eq().value(2);
- public abstract class AbstractFilter<T> {
- /**
- * Method that returns whether an item is to be included or not.
- * @param item an item from the given collection.
- * @return true if this item is to be included in the collection, false in case it has to be removed.
- */
- protected abstract boolean excludeItem(T item);
- public void filter(Collection<T> collection) {
- if (CollectionUtils.isNotEmpty(collection)) {
- Iterator<T> iterator = collection.iterator();
- while (iterator.hasNext()) {
- if (excludeItem(iterator.next())) {
- iterator.remove();
- }
- }
- }
- }
- CollectionUtils.filter(list, p -> ((Person) p).getAge() > 16);
- myProducts.stream().filter(prod -> prod.price>10).collect(Collectors.toList())
- Collection<Integer> collection = Lists.newArrayList(1, 2, 3, 4, 5);
- Iterators.removeIf(collection.iterator(), new Predicate<Integer>() {
- @Override
- public boolean apply(Integer i) {
- return i % 2 == 0;
- }
- });
- System.out.println(collection); // Prints 1, 3, 5
- public class Filter {
- public static <T> void List(List<T> list, Chooser<T> chooser) {
- List<Integer> toBeRemoved = new ArrayList<>();
- leftloop:
- for (int right = 1; right < list.size(); ++right) {
- for (int left = 0; left < right; ++left) {
- if (toBeRemoved.contains(left)) {
- continue;
- }
- Keep keep = chooser.choose(list.get(left), list.get(right));
- switch (keep) {
- case LEFT:
- toBeRemoved.add(right);
- continue leftloop;
- case RIGHT:
- toBeRemoved.add(left);
- break;
- case NONE:
- toBeRemoved.add(left);
- toBeRemoved.add(right);
- continue leftloop;
- }
- }
- }
- Collections.sort(toBeRemoved, new Comparator<Integer>() {
- @Override
- public int compare(Integer o1, Integer o2) {
- return o2 - o1;
- }
- });
- for (int i : toBeRemoved) {
- if (i >= 0 && i < list.size()) {
- list.remove(i);
- }
- }
- }
- public static <T> void List(List<T> list, Keeper<T> keeper) {
- Iterator<T> iterator = list.iterator();
- while (iterator.hasNext()) {
- if (!keeper.keep(iterator.next())) {
- iterator.remove();
- }
- }
- }
- public interface Keeper<E> {
- boolean keep(E obj);
- }
- public interface Chooser<E> {
- Keep choose(E left, E right);
- }
- public enum Keep {
- LEFT, RIGHT, BOTH, NONE;
- }
- }
- List<String> names = new ArrayList<>();
- names.add("Anders");
- names.add("Stefan");
- names.add("Anders");
- Filter.List(names, new Filter.Chooser<String>() {
- @Override
- public Filter.Keep choose(String left, String right) {
- return left.equals(right) ? Filter.Keep.LEFT : Filter.Keep.BOTH;
- }
- });
Add Comment
Please, Sign In to add comment