Java Code Examples for org.apache.commons.collections4.CollectionUtils#filter()

The following examples show how to use org.apache.commons.collections4.CollectionUtils#filter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BeanQuery.java    From bean-query with Apache License 2.0 6 votes vote down vote up
/**
 * Execute this Query. If query from a null or empty collection, an empty list
 * will be returned.
 *
 * @return
 */
public List<T> execute() {
  if (CollectionUtils.isEmpty(from)) {
    logger.info("Querying from an empty collection, returning empty list.");
    return Collections.emptyList();
  }

  List copied = new ArrayList(this.from);

  logger.info("Start apply predicate [{}] to collection with [{}] items.", predicate, copied.size());
  CollectionUtils.filter(copied, this.predicate);
  logger.info("Done filtering collection, filtered result size is [{}]", copied.size());

  if (null != this.comparator && copied.size()>1) {
    Comparator actualComparator = this.descSorting ? comparator.desc() : comparator.asc();
    logger.info("Start to sort the filtered collection with comparator [{}]", actualComparator);
    Collections.sort(copied, actualComparator);
    logger.info("Done sorting the filtered collection.");
  }

  logger.info("Start to slect from filtered collection with selector [{}].", selector);
  List<T> select = this.selector.select(copied);
  logger.info("Done select from filtered collection.");
  return select;

}
 
Example 2
Source File: VillageUtils.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public static Village[] getVillagesByContinent(Village[] pVillages, final Integer[] pContinents, Comparator<Village> pComparator) {
    if (pContinents == null || pContinents.length == 0) {
        return pVillages;
    }
    List<Village> villages = new LinkedList<>();
    Collections.addAll(villages, pVillages);

    CollectionUtils.filter(villages, new Predicate() {

        @Override
        public boolean evaluate(Object o) {
            return ArrayUtils.contains(pContinents, ((Village) o).getContinent());
        }
    });
    if (pComparator != null) {
        Collections.sort(villages, pComparator);
    }
    return villages.toArray(new Village[villages.size()]);
}
 
Example 3
Source File: AllyUtils.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public static Tribe[] getTribes(Ally pAlly, Comparator<Tribe> pComparator) {
    Tribe[] result = null;
    if (pAlly == null) {
        return new Tribe[0];
    } else if (pAlly.equals(NoAlly.getSingleton())) {
        List<Tribe> tribes = new LinkedList<>();
        CollectionUtils.addAll(tribes, DataHolder.getSingleton().getTribes().values());
        CollectionUtils.filter(tribes, new Predicate() {

            @Override
            public boolean evaluate(Object o) {
                return ((Tribe) o).getAlly() == null || ((Tribe) o).getAlly().equals(NoAlly.getSingleton());
            }
        });
        result = tribes.toArray(new Tribe[tribes.size()]);
    } else {
        result = pAlly.getTribes();
    }

    if (pComparator != null) {
        Arrays.sort(result, pComparator);
    }

    return result;
}
 
Example 4
Source File: CCFilter.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
public String[] filter(String[] values, final String prefix) {
    if (values == null) {
        return null;
    }
    if (prefix == null) {
        return values;
    }

    List<String> result = new ArrayList<>(Arrays.asList(values));
    CollectionUtils.filter(result, new Predicate<String>() {
        public boolean evaluate(String string) {
            return string != null && string.startsWith(prefix);
        }
    });
    return result.toArray(new String[result.size()]);
}
 
Example 5
Source File: CollectionUtilsGuideUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenCustomerList_whenFiltered_thenCorrectSize() {

    boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() {
        public boolean evaluate(Customer customer) {
            return Arrays.asList("Daniel", "Kyle").contains(customer.getName());
        }
    });

    // filterInverse does the opposite. It removes the element from the list if the Predicate returns true
    // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection

    assertTrue(isModified && linkedList1.size() == 2);
}
 
Example 6
Source File: JavaTransformTest.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void retainTest() {
    Collection<String> jdk = Lists.newArrayList("a1", "a2", "a3", "a1");
    Iterable<String> guava = Lists.newArrayList(jdk);
    Iterable<String> apache = Lists.newArrayList(jdk);
    MutableCollection<String> gs = FastList.newList(jdk);

    // remove if not
    jdk.removeIf((s) -> !s.contains("1")); // using jdk
    Iterables.removeIf(guava, (s) -> !s.contains("1")); // using guava
    CollectionUtils.filter(apache, (s) -> s.contains("1")); // using apache
    gs.removeIf((Predicate<String>) (s) -> !s.contains("1"));  //using gs

    System.out.println("retainIf = " + jdk + ":" + guava + ":" + apache + ":" + gs); // print retainIf = [a1, a1]:[a1, a1]:[a1, a1]:[a1, a1]
}
 
Example 7
Source File: JavaTransformTest.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void removeTest() {
    Collection<String> jdk = Lists.newArrayList("a1", "a2", "a3", "a1");
    Iterable<String> guava = Lists.newArrayList(jdk);
    Iterable<String> apache = Lists.newArrayList(jdk);
    MutableCollection<String> gs = FastList.newList(jdk);

    // remove if
    jdk.removeIf((s) -> s.contains("1")); // using jdk
    Iterables.removeIf(guava, (s) -> s.contains("1")); // using guava
    CollectionUtils.filter(apache, (s) -> !s.contains("1")); // using apache
    gs.removeIf((Predicate<String>) (s) -> s.contains("1"));  // using gs

    System.out.println("removeIf = " + jdk + ":" + guava + ":" + apache + ":" + gs); // print removeIf = [a2, a3]:[a2, a3]:[a2, a3]:[a2, a3]
}
 
Example 8
Source File: LabelDao.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private static List<StringLabel> getLabels(Locale l, final String search) {
	if (!labelCache.containsKey(l)) {
		List<StringLabel> ll = getLabels(l);
		labelCache.putIfAbsent(l, ll);
	}
	List<StringLabel> result = new ArrayList<>(labelCache.containsKey(l) ? labelCache.get(l) : new ArrayList<StringLabel>());
	if (!Strings.isEmpty(search)) {
		CollectionUtils.filter(result, o -> o != null && (o.getKey().contains(search) || o.getValue().contains(search)));
	}
	return result;
}
 
Example 9
Source File: JavaTransformTest.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void retainTest() {
    Collection<String> jdk = Lists.newArrayList("a1", "a2", "a3", "a1");
    Iterable<String> guava = Lists.newArrayList(jdk);
    Iterable<String> apache = Lists.newArrayList(jdk);
    MutableCollection<String> gs = FastList.newList(jdk);

    // удаление всех не равных условию
    jdk.removeIf((s) -> !s.contains("1")); // с помощью jdk
    Iterables.removeIf(guava, (s) -> !s.contains("1")); // с помощью guava
    CollectionUtils.filter(apache, (s) -> s.contains("1")); // с помощью apache
    gs.removeIf((Predicate<String>) (s) -> !s.contains("1"));  //с помощью gs

    System.out.println("retainIf = " + jdk + ":" + guava + ":" + apache + ":" + gs); // напечатает retainIf = [a1, a1]:[a1, a1]:[a1, a1]:[a1, a1]
}
 
Example 10
Source File: Config.java    From DBforBIX with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return a list of all VALID database configurations
 */
public Collection<Database> getDatabases() {
	Collection<Database> validDatabases = databases;
	CollectionUtils.filter(validDatabases, new Predicate<Database>() {
		
		@Override
		public boolean evaluate(Database object) {
			return ((Database) object).isValid();
		}
	});
	return validDatabases;
}
 
Example 11
Source File: Config.java    From DBforBIX with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return a list of all VALID zabbix server configurations
 */
public Collection<ZabbixServer> getZabbixServers() {
	Collection<ZabbixServer> validServers = _zabbixServers;
	CollectionUtils.filter(validServers, new Predicate <ZabbixServer>() {			
		@Override
		public boolean evaluate(ZabbixServer object) {
			return ((ZabbixServer) object).isValid();
		}
	});
	return validServers;
}
 
Example 12
Source File: MainLogicImpl.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <E> List<E> getEntities(Class<E> entityClass, Predicate<E> predicate, Integer offset, Integer limit, List<SortOrder<String>> sortOrders) {
	if (log.isTraceEnabled()) {
		log.trace("Getting " + getEntityClassName(entityClass, null) + " (offset=" + offset + ", limit=" + limit + ", sortOrders=" + ((sortOrders != null && !sortOrders.isEmpty()) ? (Arrays.toString(sortOrders.toArray(new SortOrder[sortOrders.size()]))) : "/") + ")" + " using predicate : " + predicate);
	}

	EntityPersister<E, ?> entityPersister = getEntityPersister(entityClass);
	List<E> entities = entityPersister.getAllEntities();
	if (entities == null) {
		return Collections.emptyList();
	}
	CollectionUtils.filter(entities, predicate);
	sort(entities, sortOrders);

	if (offset != null && limit != null) {
		if (offset < entities.size()) {
			entities = entities.subList(offset, Math.min(entities.size(), offset + limit));
		} else {
			entities = Collections.emptyList();
		}
	}

	if (log.isTraceEnabled()) {
		log.trace("Returned " + entities.size() + " " + getEntityClassName(entityClass, entities.size() > 1));
	}
	return entities;
}
 
Example 13
Source File: JavaCollectionCleanupUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() {
    final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    CollectionUtils.filter(list, PredicateUtils.notNullPredicate());

    assertThat(list, hasSize(3));
}
 
Example 14
Source File: SearchImpl.java    From ad with Apache License 2.0 5 votes vote down vote up
private void filterItFeature(Collection<Long> adUnitIds, ItFeature feature) {
    if (CollectionUtils.isEmpty(adUnitIds)) {
        return;
    }
    if (CollectionUtils.isNotEmpty(feature.getIts())) {
        CollectionUtils.filter(adUnitIds, adUnitId ->
                DataTable.of(UnitItIndex.class).match(adUnitId, feature.getIts())
        );
    }
}
 
Example 15
Source File: SearchImpl.java    From ad with Apache License 2.0 5 votes vote down vote up
private void filterDistrictFeature(Collection<Long> adUnitIds, DistrictFeature feature) {
    if (CollectionUtils.isEmpty(adUnitIds)) {
        return;
    }
    if (CollectionUtils.isNotEmpty(feature.getDistricts())) {
        CollectionUtils.filter(adUnitIds, adUnitId ->
                DataTable.of(UnitDistrictIndex.class).match(adUnitId, feature.getDistricts())
        );
    }
}
 
Example 16
Source File: SearchImpl.java    From ad with Apache License 2.0 5 votes vote down vote up
/**
 * and 类型过滤
 *
 * @param adUnitIds
 * @param feature
 */
private void filterKeywordFeature(Collection<Long> adUnitIds, KeywordFeature feature) {
    if (CollectionUtils.isEmpty(adUnitIds)) {
        return;
    }
    if (CollectionUtils.isNotEmpty(feature.getKeywords())) {
        CollectionUtils.filter(adUnitIds, adUnitId ->
                DataTable.of(UnitKeywordIndex.class).match(adUnitId, feature.getKeywords())
        );
    }
}
 
Example 17
Source File: SearchImpl.java    From ad with Apache License 2.0 5 votes vote down vote up
/**
 * 推广单元状态过滤
 *
 * @return
 */
private void filterAdUnitAndPlanStatus(List<AdUnitObject> unitObjects, CommonStatus commonStatus) {
    if (CollectionUtils.isEmpty(unitObjects)) {
        return;
    }
    CollectionUtils.filter(unitObjects, unitObject ->
            unitObject.getUnitStatus().equals(commonStatus.getStatus()) &&
                    unitObject.getAdPlanObject().getPlanStatus() == commonStatus.getStatus()
    );
}
 
Example 18
Source File: MenuBuilder.java    From cuba with Apache License 2.0 4 votes vote down vote up
private void createSubMenu(JMenu jMenu, MenuItem item) {
    List<MenuItem> itemChildren = new ArrayList<>(item.getChildren());
    CollectionUtils.filter(itemChildren, object -> object.isPermitted(userSession));

    List<MenuItemContainer> items = new ArrayList<>();

    // prepare menu items
    for (MenuItem child : itemChildren) {
        if (child.getChildren().isEmpty()) {
            if (child.isSeparator()) {
                items.add(new MenuItemContainer());
            } else {
                JMenuItem jMenuItem = new JMenuItem(menuConfig.getItemCaption(child.getId()));
                jMenuItem.setName(child.getId());
                assignCommand(jMenuItem, child);
                assignShortcut(jMenuItem, child);
                items.add(new MenuItemContainer(jMenuItem));
            }
        } else {
            JMenu jChildMenu = new JMenu(menuConfig.getItemCaption(child.getId()));
            createSubMenu(jChildMenu, child);
            if (!isMenuEmpty(jChildMenu)) {
                items.add(new MenuItemContainer(jChildMenu));
            }
        }
    }

    // remove unnecessary separators
    if (!items.isEmpty()) {
        Iterator<MenuItemContainer> iterator = items.iterator();
        JMenuItem menuItem = getNextMenuItem(iterator);
        boolean useSeparator = false;

        while (menuItem != null) {
            if (useSeparator)
                jMenu.addSeparator();

            jMenu.add(menuItem);

            useSeparator = false;
            menuItem = null;

            if (iterator.hasNext()) {
                MenuItemContainer itemContainer = iterator.next();
                if (!itemContainer.isSeparator())
                    menuItem = itemContainer.getMenuItem();
                else {
                    menuItem = getNextMenuItem(iterator);
                    useSeparator = true;
                }
            }
        }
    }
}
 
Example 19
Source File: CollectionUtilsCollectionFilter.java    From tutorials with MIT License 4 votes vote down vote up
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
    Predicate<Integer> apacheEventNumberPredicate = item -> item % 2 == 0;

    CollectionUtils.filter(baseCollection, apacheEventNumberPredicate);
    return baseCollection;
}
 
Example 20
Source File: ComWorkflowDaoImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<Workflow> getDependentWorkflows(@VelocityCheck int companyId, Collection<WorkflowDependency> dependencies, boolean exceptInactive) {
    final Set<WorkflowDependency> filteredDependencies = new HashSet<>(CollectionUtils.emptyIfNull(dependencies));
    CollectionUtils.filter(filteredDependencies, PredicateUtils.notNullPredicate());
    if (companyId <= 0 || filteredDependencies.isEmpty()) {
        return Collections.emptyList();
    }

    StringBuilder sqlBuilder = new StringBuilder();
    List<Object> sqlParameters = new ArrayList<>();

    sqlBuilder.append("SELECT w.* FROM workflow_tbl w ")
            .append("JOIN workflow_dependency_tbl dep ON dep.workflow_id = w.workflow_id AND dep.company_id = w.company_id ")
            .append("WHERE w.company_id = ?  ");

    sqlParameters.add(companyId);

    sqlBuilder.append("AND ( ");
    boolean isFirstDependency = true;
    for(WorkflowDependency dependency : filteredDependencies) {
        if(!isFirstDependency){
            sqlBuilder.append(" OR");
        }
        isFirstDependency = false;

        sqlBuilder.append("(dep.type = ? ");
        sqlParameters.add(dependency.getType().getId());

        if (dependency.getEntityId() > 0) {
            sqlBuilder.append("AND dep.entity_id = ? ");
            sqlParameters.add(dependency.getEntityId());
        } else {
            sqlBuilder.append("AND dep.entity_name = ? ");
            sqlParameters.add(dependency.getEntityName());
        }
        sqlBuilder.append(" )");
    }
    sqlBuilder.append(" )");

    if (exceptInactive) {
        sqlBuilder.append("AND w.status IN (?, ?) ");
        sqlParameters.add(WorkflowStatus.STATUS_ACTIVE.getId());
        sqlParameters.add(WorkflowStatus.STATUS_TESTING.getId());
    }

    sqlBuilder.append("ORDER BY w.workflow_id DESC");

    return select(logger, sqlBuilder.toString(), new WorkflowRowMapper(), sqlParameters.toArray());
}