本文整理汇总了Java中java.util.List.removeIf方法的典型用法代码示例。如果您正苦于以下问题:Java List.removeIf方法的具体用法?Java List.removeIf怎么用?Java List.removeIf使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.List
的用法示例。
在下文中一共展示了List.removeIf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: channelActive
import java.util.List; //导入方法依赖的package包/类
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
logger.info("通道重置");
List<ChannelPipeline> channelPipelines = tcpMediator.getSendingMsgRepo().getChannelPipelines();
channelPipelines.add(ctx.pipeline());
channelPipelines.removeIf(channel -> {
i++;
if (channel == null || !channel.channel().isActive()) {
logger.info("「" + i + "」" + "通道失效");
return true;
} else {
logger.info("「" + i + "」" + "通道有效");
return false;
}
});
i = 0;
logger.info("通道数量:" + channelPipelines.size());
}
示例2: duelIfCrowded
import java.util.List; //导入方法依赖的package包/类
public static void duelIfCrowded(World world, NemesisEntry exclude, boolean onlyIfCrowded) {
List<NemesisEntry> nemeses = NemesisRegistryProvider.get(world).list();
nemeses.removeIf(NemesisEntry::isDead);
if (onlyIfCrowded && nemeses.size() < NemesisConfig.NEMESIS_LIMIT) {
return;
}
nemeses.removeIf(NemesisEntry::isSpawned);
if (exclude != null) {
nemeses.removeIf((NemesisEntry n) -> n.getId().equals(exclude.getId()));
}
if (nemeses.size() < 2) {
return;
}
//TODO factor in distance, the closer the nemeses the more likely they should be to duelIfCrowded
// get the weaklings
Collections.shuffle(nemeses);
nemeses.sort(Comparator.comparingInt(NemesisEntry::getLevel));
duel(world, nemeses.get(0), nemeses.get(1));
}
示例3: testRemoveIfThrowsCME
import java.util.List; //导入方法依赖的package包/类
@Test
public void testRemoveIfThrowsCME() {
@SuppressWarnings("unchecked")
final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
final List<Integer> list = test.collection;
if (list.size() <= 1) {
continue;
}
boolean gotException = false;
try {
// bad predicate that modifies its list, should throw CME
list.removeIf(list::add);
} catch (ConcurrentModificationException cme) {
gotException = true;
}
if (!gotException) {
fail("expected CME was not thrown from " + test);
}
}
}
示例4: findEmptyShard
import java.util.List; //导入方法依赖的package包/类
/**
* Finds an existing empty shard, or returns null if none exist.
*/
private static Shard findEmptyShard(RangeShardMap<Integer> shardMap) {
// Get all shards in the shard map (ordered by name)
List<Shard> allShards = shardMap.getShards().stream().sorted(Comparator.comparing(shard -> shard.getLocation().getDatabase()))
.collect(Collectors.toList());
// Get all mappings in the shard map
List<RangeMapping> allMappings = shardMap.getMappings();
// Determine which shards have mappings
Set<UUID> shardsIdsWithMappings = allMappings.stream().map(RangeMapping::getShard).map(Shard::getId).collect(Collectors.toSet());
// Remove all the shards that has mappings
allShards.removeIf(shard -> shardsIdsWithMappings.contains(shard.getId()));
// Get the first shard, if it exists
return Iterables.getFirst(allShards, null);
}
示例5: getList
import java.util.List; //导入方法依赖的package包/类
private static List<String> getList(final String fileName) {
final List<String> lines = new ArrayList<>();
Optional.ofNullable(UtteranceGenerator.class.getResource(fileName)).ifPresent(url -> {
final File file = new File(url.getFile());
try (final Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
scanner.close();
} catch (final IOException e) {
e.printStackTrace();
}
});
// eliminate empty lines
lines.removeIf(StringUtils::isBlank);
// eliminate commentary
lines.removeIf(line -> line.startsWith("//"));
return lines;
}
示例6: removeObserverFromObserverList
import java.util.List; //导入方法依赖的package包/类
private static void removeObserverFromObserverList(NotificationObserver observer, List<NotificationObserver> observerList) {
observerList.removeIf(actualObserver -> actualObserver.equals(observer));
observerList.removeIf(actualObserver -> {
if(actualObserver instanceof WeakNotificationObserver) {
WeakNotificationObserver weakObserver = (WeakNotificationObserver) actualObserver;
NotificationObserver wrappedObserver = weakObserver.getWrappedObserver();
if(wrappedObserver == null) { // if reference was GCed we can remove the weakObserver
return true;
} else {
return wrappedObserver.equals(observer);
}
}
return false;
});
}
示例7: execute
import java.util.List; //导入方法依赖的package包/类
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
List<Camera> cams = new ArrayList<>(plugin.getCameras().values());
cams.removeIf((cam)-> !cam.canUseCamera(src));
Iterable<Text> texts = cams.parallelStream().map((cam)->
plugin.translations.CAMERA_LIST_ITEM.apply(cam.templateVariables())
.onHover(TextActions.showText(
plugin.translations.CAMERA_LIST_ITEM_HOVER.apply(cam.templateVariables()).build()
))
.onClick(TextActions.runCommand("/camera view " + cam.getId())).build()
).collect(Collectors.toList());
PaginationList.builder()
.title(plugin.translations.CAMERA_LIST_TITLE)
.contents(texts)
.sendTo(src);
return CommandResult.success();
}
示例8: incrementalSweepingOfUnreachableIterators
import java.util.List; //导入方法依赖的package包/类
/**
* Checks incremental sweeping of unreachable iterators.
* Excessively white box?!
*/
public void incrementalSweepingOfUnreachableIterators() {
boolean fair = rnd.nextBoolean();
int capacity = rnd.nextInt(10, 20);
ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair);
randomizePutIndex(q);
final int SHORT_SWEEP_PROBES = 4;
final int LONG_SWEEP_PROBES = 16;
final int PROBE_HOP = LONG_SWEEP_PROBES + 6 * SHORT_SWEEP_PROBES;
final int PROBE_HOP_COUNT = 10;
// Expect around 8 sweeps per PROBE_HOP
final int SWEEPS_PER_PROBE_HOP = 8;
List<Iterator> its = new ArrayList<>();
for (int i = 0; i < capacity; i++)
q.add(i);
for (int i = 0; i < PROBE_HOP_COUNT * PROBE_HOP; i++)
its.add(q.iterator());
assertEquals(attachedIterators(q), its);
// make some garbage, separated by PROBE_HOP
for (int i = 0; i < its.size(); i += PROBE_HOP)
its.set(i, null);
its.removeIf(it -> it == null);
forceFullGc();
int retries;
for (retries = 0;
trackedIterators(q).contains(null) && retries < 1000;
retries++)
// one round of sweeping
its.add(q.iterator());
assertTrue(retries >= PROBE_HOP_COUNT * (SWEEPS_PER_PROBE_HOP - 2));
assertTrue(retries <= PROBE_HOP_COUNT * (SWEEPS_PER_PROBE_HOP + 2));
assertEquals(trackedIterators(q), its);
}
示例9: verifyUpgrades
import java.util.List; //导入方法依赖的package包/类
public static void verifyUpgrades(TileEntity tile,List<IUpgradeProvider> list)
{
//Count, remove, sort
//This call is expensive. Ideally should be cached.
HashMap<String,Integer> upgradeCounts = new HashMap<>();
list.forEach(x -> {
String id = x.getUpgradeId();
upgradeCounts.put(x.getUpgradeId(), upgradeCounts.containsKey(id) ? upgradeCounts.get(x.getUpgradeId()) : 1);
});
list.removeIf(x -> upgradeCounts.get(x.getUpgradeId()) > x.getLimit(tile));
list.sort((x,y) -> Integer.compare(x.getPriority(),y.getPriority()));
}
示例10: getSerialisers
import java.util.List; //导入方法依赖的package包/类
private static List<Serialiser> getSerialisers() {
final List<Serialiser> serialisers = getSubClassInstances(Serialiser.class);
serialisers.removeIf(c -> {
boolean contains = false;
for (final ToBytesSerialiser serialiser : TO_BYTES_SERIALISERS) {
if (serialiser.getClass().equals(c.getClass())) {
contains = true;
break;
}
}
return contains;
});
return serialisers;
}
示例11: doReduce
import java.util.List; //导入方法依赖的package包/类
@Override
public InternalAggregation doReduce(final List<InternalAggregation> aggregations,
final ReduceContext reduceContext) {
// merge samples across all shards
final List<InternalAggregation> aggs = new ArrayList<>(aggregations);
aggs.removeIf(p -> ((BaseInternalAggregation) p).sampling == null);
// return empty result if all samples are null
if (aggs.isEmpty()) {
return buildEmptyInternalAggregation();
}
final S composedSampling = buildSampling(this.featuresCount);
for (int i = 0; i < aggs.size(); ++i) {
LOGGER.debug("Merging sampling={}: {}", i, ((BaseInternalAggregation) aggs.get(i)).sampling);
//noinspection unchecked
composedSampling.merge((S) ((BaseInternalAggregation) aggs.get(i)).sampling);
}
if (composedSampling.getCount() <= composedSampling.getFeaturesCount()) {
LOGGER.debug(
"Insufficient amount of training data for model estimation, at least {} are required, given {}",
composedSampling.getFeaturesCount() + 1, composedSampling.getCount());
return buildEmptyInternalAggregation();
}
M evaluatedResults = null;
try {
evaluatedResults = evaluateResults(composedSampling);
} catch (final EstimationException e) {
LOGGER.debug(
"Failed to estimate model", e);
return buildEmptyInternalAggregation();
}
LOGGER.debug("Evaluated results: {}", evaluatedResults);
return buildInternalAggregation(this.name, this.featuresCount, composedSampling,
evaluatedResults,
pipelineAggregators(), getMetaData());
}
示例12: superMethods
import java.util.List; //导入方法依赖的package包/类
private static List<MethodSignatureBackedByPsiMethod> superMethods(PsiMethod method) {
List<MethodSignatureBackedByPsiMethod> signatures = method.findSuperMethodSignaturesIncludingStatic(true);
signatures.removeIf(superSignature ->
superSignature.getMethod().getParameterList().getParametersCount()
!= method.getParameterList().getParametersCount());
return signatures;
}
开发者ID:stylismo,项目名称:nullability-annotations-inspection,代码行数:8,代码来源:NullabilityAnnotationsWithTypeQualifierDefault.java
示例13: doScan
import java.util.List; //导入方法依赖的package包/类
@Override
public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse());
IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest());
if (resp == null | req == null) return null;
URL url = helpers.analyzeRequest(baseRequestResponse).getUrl();
if (flags.contains(url.toString())) return null;
else flags.add(url.toString());
IBurpCollaboratorClientContext collaboratorContext = callbacks.createBurpCollaboratorClientContext();
String collaboratorPayload = collaboratorContext.generatePayload(true);
List<IScanIssue> issues = new ArrayList<>();
for (String xxe : XXEPayloads) {
xxe = xxe.replace("{collaboratorPayload}", collaboratorPayload);
List<String> headers = helpers.analyzeRequest(baseRequestResponse).getHeaders();
headers.set(0, headers.get(0).replace("GET", "POST"));
headers.removeIf(header -> header != null && header.toLowerCase().startsWith("content-type:"));
headers.add("Content-type: application/xml");
byte[] attackBody = helpers.buildHttpMessage(headers, helpers.stringToBytes(xxe));
IHttpRequestResponse attackRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), attackBody);
List<IBurpCollaboratorInteraction> collaboratorInteractions = collaboratorContext.fetchCollaboratorInteractionsFor(collaboratorPayload);
if (attackRequestResponse != null && attackRequestResponse.getResponse() != null
&& collaboratorInteractions != null
&& (!collaboratorInteractions.isEmpty() || helpers.bytesToString(attackRequestResponse.getResponse()).contains("dryat0Uct333"))) {
String attackDetails = "XXE processing is enabled at: \n" + helpers.analyzeRequest(attackRequestResponse).getUrl().toString();
issues.add(new CustomScanIssue(attackRequestResponse.getHttpService(),
helpers.analyzeRequest(attackRequestResponse).getUrl(),
new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, null)},
attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE,
"", "", ""));
}
}
return issues.isEmpty() ? null : issues;
}
示例14: doScan
import java.util.List; //导入方法依赖的package包/类
@Override
public List<IScanIssue> doScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
IResponseInfo resp = helpers.analyzeResponse(baseRequestResponse.getResponse());
IRequestInfo req = helpers.analyzeRequest(baseRequestResponse.getRequest());
if (resp == null | req == null) return null;
URL url = helpers.analyzeRequest(baseRequestResponse).getUrl();
if (flags.contains(url.toString())) return null;
else flags.add(url.toString());
List<IScanIssue> issues = new ArrayList<>();
List<String> headers = helpers.analyzeRequest(baseRequestResponse).getHeaders();
headers.set(0, headers.get(0).replace("GET", "POST"));
headers.removeIf(header -> header != null && header.toLowerCase().startsWith("content-type:"));
headers.add("Content-type: application/xml;charset=UTF-8");
byte[] attackBody = helpers.buildHttpMessage(headers, helpers.stringToBytes(PAYLOAD));
IHttpRequestResponse attackRequestResponse = callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), attackBody);
if (attackRequestResponse != null && attackRequestResponse.getResponse() != null
&& helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("faultcode")
&& (helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("http://ws.apache.org/xmlrpc/namespaces/extensions")
|| helpers.bytesToString(attackRequestResponse.getResponse()).toLowerCase().contains("org.hibernate.engine.spi.typedvalue"))) {
String attackDetails = "The application deserialize untrusted serialized Java objects at <b>" +
helpers.analyzeRequest(attackRequestResponse).getUrl().toString() +
"</b> without first checking the type of the received object. This issue can be" +
" exploited by sending malicious objects that, when deserialized," +
" execute custom Java code.";
issues.add(new CustomScanIssue(attackRequestResponse.getHttpService(),
helpers.analyzeRequest(attackRequestResponse).getUrl(),
new IHttpRequestResponse[]{callbacks.applyMarkers(attackRequestResponse, null, null)},
attackDetails, ISSUE_TYPE, ISSUE_NAME, SEVERITY, CONFIDENCE,
"", "", ""));
}
return issues.isEmpty() ? null : issues;
}
示例15: immunizationDue
import java.util.List; //导入方法依赖的package包/类
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean immunizationDue(String immunization, Person person, long time,
Map<String, List<Long>> immunizationsGiven) {
int ageInMonths = person.ageInMonths(time);
List<Long> history = null;
if (immunizationsGiven.containsKey(immunization)) {
history = immunizationsGiven.get(immunization);
} else {
history = new ArrayList<Long>();
immunizationsGiven.put(immunization, history);
}
// Don't administer if the immunization wasn't historically available at the date of the
// encounter
Map schedule = immunizationSchedule.get(immunization);
Double firstAvailable = (Double) schedule.getOrDefault("first_available", 1900);
if (time < Utilities.convertCalendarYearsToTime(firstAvailable.intValue())) {
return false;
}
// Don't administer if all recommended doses have already been given
List atMonths = new ArrayList((List) schedule.get("at_months"));
if (history.size() >= atMonths.size()) {
return false;
}
// See if the patient should receive a dose based on their current age and the recommended dose
// ages;
// we can't just see if greater than the recommended age for the next dose they haven't received
// because i.e. we don't want to administer the HPV vaccine to someone who turns 90 in 2006 when
// the
// vaccine is released; we can't just use a simple test of, say, within 4 years after the
// recommended
// age for the next dose they haven't received because i.e. PCV13 is given to kids and seniors
// but was
// only available starting in 2010, so a senior in 2012 who has never received a dose should get
// one,
// but only one; what we do is:
// 1) eliminate any recommended doses that are not within 4 years of the patient's age
// at_months = at_months.reject { |am| age_in_months - am >= 48 }
Predicate<Double> notWithinFourYears = p -> ((ageInMonths - p) >= 48);
atMonths.removeIf(notWithinFourYears);
if (atMonths.isEmpty()) {
return false;
}
// 2) eliminate recommended doses that were actually administered
for (Long date : history) {
int ageAtDate = person.ageInMonths(date);
double recommendedAge = (double) atMonths.get(0);
if (ageAtDate >= recommendedAge && ((ageAtDate - recommendedAge) < 48)) {
atMonths.remove(0);
if (atMonths.isEmpty()) {
return false;
}
}
}
// 3) see if there are any recommended doses remaining that this patient is old enough for
return !atMonths.isEmpty() && ageInMonths >= (double) atMonths.get(0);
}