Java tutorial
//package com.java2s; /* * Copyright (c) 2013 The Finnish National Board of Education - Opetushallitus * * This program is free software: Licensed under the EUPL, Version 1.1 or - as * soon as they will be approved by the European Commission - subsequent versions * of the EUPL (the "Licence"); * * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * European Union Public Licence for more details. */ import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.*; public class Main { /** * @param col to filter using Collections2.filter * @param predicate to use * @param fallbackPredicate to use if predicate resulted in empty collection * @param <T> type contained in the collection * @return the filtered collection */ public static <T> Collection<T> filter(Collection<T> col, Predicate<? super T> predicate, Predicate<? super T> fallbackPredicate) { Collection<T> result = Collections2.filter(col, predicate); if (result.isEmpty()) { return Collections2.filter(col, fallbackPredicate); } return result; } /** * @param original function, result of which to filter * @param filter to apply to function results * @param <E> * @param <T> * @param <C> * @return a function that wraps the given original function in a function that filters the result of it with * given filter */ public static <E, T, C extends List<T>> Function<E, List<T>> filter(final Function<E, C> original, final Predicate<T> filter) { return new Function<E, List<T>>() { public List<T> apply(E input) { return new ArrayList<T>(Collections2.filter(original.apply(input), filter)); } }; } }