下面列出了java.util.Collection#removeIf ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void runBasicRemoveIfTests(Supplier<Collection<Integer>> supp) {
Collection<Integer> integers = supp.get();
for (int h = 0; h < 100; ++h) {
// Insert some ordered integers.
integers.add(h);
}
integers.removeIf(isEven);
Integer prev = null;
for (Integer i : integers) {
assertTrue(i % 2 != 0);
if (prev != null) {
assertTrue(prev <= i);
}
prev = i;
}
integers.removeIf(isOdd);
assertTrue(integers.isEmpty());
}
private void addReflectionForName(String className, boolean isInterface, IndexView indexView,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass, boolean methods, boolean fields,
Set<DotName> excludedClasses) {
Collection<ClassInfo> classInfos;
if (isInterface) {
classInfos = indexView.getAllKnownImplementors(DotName.createSimple(className));
} else {
classInfos = indexView.getAllKnownSubclasses(DotName.createSimple(className));
}
classInfos.removeIf(ci -> excludedClasses.contains(ci.name()));
if (!classInfos.isEmpty()) {
reflectiveClass.produce(new ReflectiveClassBuildItem(methods, fields,
classInfos.stream().map(ClassInfo::toString).toArray(String[]::new)));
}
}
/****
* remove specify value frome list
* default remove null or blank string
* @param collection
* @param stripValue
* @return
*/
public static Collection strip(Collection<?> collection, final Object... stripValue) {
collection.removeIf(obj-> {
if (obj instanceof Class) {
if (ArrayUtils.isAssignableFrom(stripValue, (Class) obj))
return true;
} else if (obj == null || (String.class.isAssignableFrom(obj.getClass()) && StringUtils.isBlank(obj.toString())) || ArrayUtils.contains(stripValue, obj)){
return true;
}
return false;
});
return collection;
}
@Override
public Collection<IAgent> allAtDistance(final IScope scope, final IShape source, final double dist,
final IAgentFilter f) {
// TODO filter result by topology's bounds
final double exp = dist * Maths.SQRT2;
final Envelope3D env = Envelope3D.of(source.getEnvelope());
env.expandBy(exp);
try {
final Collection<IAgent> result = findIntersects(scope, source, env, f);
if (result.isEmpty()) { return GamaListFactory.create(); }
result.removeIf(each -> source.euclidianDistanceTo(each) > dist);
return result;
} finally {
env.dispose();
}
}
public static void runBasicRemoveIfTestsUnordered(Supplier<Collection<Integer>> supp) {
Collection<Integer> integers = supp.get();
for (int h = 0; h < 100; ++h) {
// Insert a bunch of arbitrary integers.
integers.add((h >>> 2) ^ (h >>> 5) ^ (h >>> 11) ^ (h >>> 17));
}
integers.removeIf(isEven);
for (Integer i : integers) {
assertTrue(i % 2 != 0);
}
integers.removeIf(isOdd);
assertTrue(integers.isEmpty());
}
/**
* PCGenActionMap and PCGenAction dynamically construct keys. All keys
* starting with the pattern used in those classes will be deemed present
* and removed from the missing keys set.
*
* @param missingKeys The list of missing keys
*/
private static void actionWhitelistedKeys(Collection<String> missingKeys)
{
missingKeys.removeIf(key ->
key.startsWith("in_mnu")
|| key.startsWith("in_mn_mnu")
|| key.startsWith("in_EqBuilder_")
|| key.startsWith("PrerequisiteOperator.display")
);
}
/**
* Method filter()
*
* @see msi.gama.metamodel.topology.filter.IAgentFilter#filter(msi.gama.runtime.IScope,
* msi.gama.metamodel.shape.IShape, java.util.Collection)
*/
@Override
public void filter(final IScope scope, final IShape source, final Collection<? extends IShape> results) {
final IAgent sourceAgent = source == null ? null : source.getAgent();
results.remove(sourceAgent);
final Predicate<IShape> toRemove = (each) -> {
final IAgent a = each.getAgent();
return a == null || a.dead()
|| a.getPopulation() != this
&& (a.getPopulation().getGamlType().getContentType() != this.getGamlType().getContentType()
|| !this.contains(a));
};
results.removeIf(toRemove);
}
@Override
public void removeAttribute(String name) {
Collection<RoleAttributeEntity> attributes = role.getAttributes();
if (attributes == null) {
return;
}
Query query = em.createNamedQuery("deleteRoleAttributesByNameAndUser");
query.setParameter("name", name);
query.setParameter("roleId", role.getId());
query.executeUpdate();
attributes.removeIf(attribute -> attribute.getName().equals(name));
}
private Collection<JSGraphQLEndpointTypeResult<JSGraphQLEndpointInterfaceTypeDefinition>> getAvailableInterfaceNames(PsiElement implementsToken, boolean autoImport) {
final Collection<JSGraphQLEndpointTypeResult<JSGraphQLEndpointInterfaceTypeDefinition>> available = getKnownInterfaceNames(implementsToken, autoImport);
final JSGraphQLEndpointImplementsInterfacesImpl implementsInterfaces = PsiTreeUtil.getParentOfType(implementsToken, JSGraphQLEndpointImplementsInterfacesImpl.class);
if (implementsInterfaces != null) {
final List<String> currentInterfaces = implementsInterfaces.getNamedTypeList().stream().map(type -> type.getIdentifier().getText()).collect(Collectors.toList());
available.removeIf(t -> currentInterfaces.contains(t.name));
}
return available;
}
@Test
public void replacing() {
final Collection<SimpleMetric> expected = new ArrayList<>(METRICES);
expected.removeIf((x) -> MetricName.valueOf(REPLACE_NAME).equals(x.getName()));
expected.add(new SimpleMetric(MetricName.valueOf(REPLACE_NAME), "has been replaced"));
SimpleMetricGroup grp = new SimpleMetricGroup(GROUP_NAME, METRICES);
grp.add(new SimpleMetric(MetricName.valueOf(REPLACE_NAME), "has been replaced"));
assertEquals(to_set_(expected), to_set_(grp.getMetrics()));
}
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]
}
/**
* {@inheritDoc}
*/
@Override
public void applyFederationFilter(final Collection list, final Class objectType) {
final Set<Long> manageableCategoryIds = getManageableContentIds();
list.removeIf(cn -> !manageableCategoryIds.contains(((ContentDTO) cn).getContentId()));
}
/**
* Remove the given notification IDs from the list of notifications.
*
* @param notifications Notifications to delete from
* @param ids Notification IDs to delete
*/
public static void removeNotifications(
final Collection<Notification> notifications, final Collection<String> ids) {
notifications.removeIf(
notification -> {
if (!notification.getId().isPresent()) {
return true;
}
return ids.contains(notification.getId().get());
});
// clear out the original set of IDs to delete
ids.clear();
}
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]
}
private Collection<TestNode> findExtraConnections(final TestNode testNode) {
final Collection<TestNode> extraConnections = new HashSet<>(nodes);
extraConnections.removeIf(next -> hasConnection(testNode, next) || testNode == next);
return extraConnections;
}
private static void demoRemoveIf(Collection<String> collection) {
System.out.println("collection: " + collection);
System.out.println("Calling list.removeIf(e -> Two.equals(e))...");
collection.removeIf(e -> "Two".equals(e));
System.out.println("collection: " + collection);
}
protected void filterToleratedElements(@NotNull Collection<? extends PsiModifierListOwner> definedMethods) {
definedMethods.removeIf(definedMethod -> PsiAnnotationSearchUtil.isAnnotatedWith(definedMethod, Tolerate.class));
}
/**
* Various ways of traversing a collection yield same elements
*/
public void testTraversalEquivalence() {
Collection c = impl.emptyCollection();
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int n = rnd.nextInt(6);
for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
ArrayList iterated = new ArrayList();
ArrayList iteratedForEachRemaining = new ArrayList();
ArrayList tryAdvanced = new ArrayList();
ArrayList spliterated = new ArrayList();
ArrayList splitonced = new ArrayList();
ArrayList forEached = new ArrayList();
ArrayList streamForEached = new ArrayList();
ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
ArrayList removeIfed = new ArrayList();
for (Object x : c) iterated.add(x);
c.iterator().forEachRemaining(iteratedForEachRemaining::add);
for (Spliterator s = c.spliterator();
s.tryAdvance(tryAdvanced::add); ) {}
c.spliterator().forEachRemaining(spliterated::add);
{ // trySplit returns "strict prefix"
Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
if (s2 != null) s2.forEachRemaining(splitonced::add);
s1.forEachRemaining(splitonced::add);
}
c.forEach(forEached::add);
c.stream().forEach(streamForEached::add);
c.parallelStream().forEach(parallelStreamForEached::add);
c.removeIf(e -> { removeIfed.add(e); return false; });
boolean ordered =
c.spliterator().hasCharacteristics(Spliterator.ORDERED);
if (c instanceof List || c instanceof Deque)
assertTrue(ordered);
HashSet cset = new HashSet(c);
assertEquals(cset, new HashSet(parallelStreamForEached));
if (ordered) {
assertEquals(iterated, iteratedForEachRemaining);
assertEquals(iterated, tryAdvanced);
assertEquals(iterated, spliterated);
assertEquals(iterated, splitonced);
assertEquals(iterated, forEached);
assertEquals(iterated, streamForEached);
assertEquals(iterated, removeIfed);
} else {
assertEquals(cset, new HashSet(iterated));
assertEquals(cset, new HashSet(iteratedForEachRemaining));
assertEquals(cset, new HashSet(tryAdvanced));
assertEquals(cset, new HashSet(spliterated));
assertEquals(cset, new HashSet(splitonced));
assertEquals(cset, new HashSet(forEached));
assertEquals(cset, new HashSet(streamForEached));
assertEquals(cset, new HashSet(removeIfed));
}
if (c instanceof Deque) {
Deque d = (Deque) c;
ArrayList descending = new ArrayList();
ArrayList descendingForEachRemaining = new ArrayList();
for (Iterator it = d.descendingIterator(); it.hasNext(); )
descending.add(it.next());
d.descendingIterator().forEachRemaining(
e -> descendingForEachRemaining.add(e));
Collections.reverse(descending);
Collections.reverse(descendingForEachRemaining);
assertEquals(iterated, descending);
assertEquals(iterated, descendingForEachRemaining);
}
}
private boolean removeWithResult(Collection<IRecipe> from)
{
return from.removeIf(this::matchesOutput);
}
public static Collection<Person> readPersonsByNameAndRoleType(final String name, final RoleType roleType) {
final Collection<Person> people = findPerson(name);
people.removeIf(person -> !roleType.isMember(person.getUser()));
return people;
}