Example usage for java.util Set removeIf

List of usage examples for java.util Set removeIf

Introduction

In this page you can find the example usage for java.util Set removeIf.

Prototype

default boolean removeIf(Predicate<? super E> filter) 

Source Link

Document

Removes all of the elements of this collection that satisfy the given predicate.

Usage

From source file:ddf.catalog.transformer.csv.common.CsvTransformer.java

/**
 * Given a list of {@link Metacard}s and a string set of requested attributes, returns a set of
 * {@link AttributeDescriptor}s containing the requested attributes.
 *///from  w  ww  .j  ava2  s  .c  o  m
public static Set<AttributeDescriptor> getOnlyRequestedAttributes(final List<Metacard> metacards,
        final Set<String> requestedAttributes) {
    final Set<AttributeDescriptor> attributes = getAllCsvAttributeDescriptors(metacards);

    // Filter out attributes not requested.
    attributes.removeIf(attrDesc -> !requestedAttributes.contains(attrDesc.getName()));

    return attributes;
}

From source file:io.dockstore.webservice.helpers.EntryVersionHelper.java

public List<T> filterContainersForHiddenTags(List<T> entries) {
    for (T entry : entries) {
        dao.evict(entry);/*from   w w w .  j  a  v a2s  .c  o m*/
        // clear users which are also lazy loaded
        entry.setUsers(null);
        // need to have this evict so that hibernate does not actually delete the tags and users
        Set<Version> versions = entry.getVersions();
        versions.removeIf(Version::isHidden);
    }
    return entries;
}

From source file:com.joyent.manta.client.MantaMetadata.java

/**
 * Removes all metadata with keys prefixed by <code>e-</code>.
 *///from www . j  av a2  s .c  o  m
public void removeAllEncrypted() {
    final Set<Map.Entry<String, String>> set = entrySet();

    set.removeIf(entry -> entry.getKey().startsWith(ENCRYPTED_METADATA_PREFIX));
}

From source file:com.jwebmp.plugins.datatable.DataTablesServlet.java

@Override
@SuppressWarnings("unchecked")
public void perform() {
    HttpServletRequest request = GuiceContext.get(GuicedServletKeys.getHttpServletRequestKey());
    StringBuilder output = new StringBuilder();
    Set<Class<? extends DataTableDataFetchEvent>> allEvents = new HashSet(GuiceContext.instance()
            .getScanResult().getSubclasses(DataTableDataFetchEvent.class.getCanonicalName()).loadClasses());
    Map<String, String[]> params = request.getParameterMap();
    String className = params.get("c")[0];
    allEvents.removeIf(a -> !a.getCanonicalName().equals(className.replace(CHAR_UNDERSCORE, CHAR_DOT)));
    if (allEvents.isEmpty()) {
        writeOutput(output, HTML_HEADER_JAVASCRIPT, UTF8_CHARSET);
        DataTablesServlet.log.fine("DataTablesServlet could not find any specified data search class");
    } else {//from   w w  w.ja va 2 s.com
        DataTableSearchRequest searchRequest = new DataTableSearchRequest();
        searchRequest.fromRequestMap(params);
        try {
            Class<? extends DataTableDataFetchEvent> event = allEvents.iterator().next();
            DataTableDataFetchEvent dtd = GuiceContext.get(event);
            DataTableData d = dtd.returnData(searchRequest);
            output.append(d.toString());
            writeOutput(output, HTML_HEADER_JSON, UTF8_CHARSET);
        } catch (Exception e) {
            output.append(ExceptionUtils.getStackTrace(e));
            writeOutput(output, HTML_HEADER_JAVASCRIPT, UTF8_CHARSET);
            DataTablesServlet.log.log(Level.SEVERE, "Unable to execute datatables ajax data fetch", e);
        }
    }
}

From source file:eu.ggnet.dwoss.redtape.reporting.RedTapeCloserOperation.java

private Set<Document> findCloseableBlocker() {
    Collection<Long> receipts = receiptCustomers.getReceiptCustomers().values();
    List<Dossier> openDossiers = new DossierEao(redTapeEm).findByClosed(false).stream()
            .filter(d -> !receipts.contains(d.getCustomerId())).collect(Collectors.toList());

    //all active blockers from open dossiers
    Set<Document> blocker = openDossiers.stream().filter(d -> !d.getActiveDocuments(BLOCK).isEmpty())
            .map(d -> d.getActiveDocuments(BLOCK)).flatMap(Collection::stream).collect(Collectors.toSet());

    //directly closable, only comment positions
    Set<Document> closable = blocker.stream()
            .filter(d -> d.getPositions().values().stream().allMatch(p -> p.getType() == COMMENT))
            .collect(Collectors.toSet());

    //documents containing at least one unit type position
    Set<Document> containsUnit = blocker.stream()
            .filter(d -> d.getPositions().values().stream().anyMatch(p -> p.getType() == UNIT))
            .collect(Collectors.toSet());

    //remove all documents where at least one unit is still in stock
    containsUnit.removeIf(d -> d.getPositions().values().stream()
            .anyMatch(p -> p.getType() == UNIT && suEao.findByUniqueUnitId(p.getUniqueUnitId()) != null));

    closable.addAll(containsUnit);/*from   w  w w  .java2 s.c  om*/

    return closable;
}

From source file:blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.java

public void removeConnection(World world, Connection con, Vec3d vecStart, Vec3d vecEnd) {
    if (con == null || world == null)
        return;//from ww  w.j av  a2  s.c  o m
    int dim = world.provider.getDimension();
    resetCachedIndirectConnections(world, con.start);
    Map<BlockPos, Set<Connection>> connsInDim = getMultimap(world.provider.getDimension());
    Set<Connection> reverseConns = connsInDim.get(con.end);
    Set<Connection> forwardConns = connsInDim.get(con.start);
    Optional<Connection> back = reverseConns.stream().filter(con::hasSameConnectors).findAny();
    reverseConns.removeIf(con::hasSameConnectors);
    forwardConns.removeIf(con::hasSameConnectors);
    Map<BlockPos, BlockWireInfo> mapForDim = blockWireMap.lookup(world.provider.getDimension());
    BiConsumer<BlockPos, Map<BlockPos, BlockWireInfo>> handle = (p, map) -> {
        if (mapForDim != null) {
            BlockWireInfo info = map.get(p);
            if (info != null) {
                for (int i = 0; i < 2; i++) {
                    Set<Triple<Connection, Vec3d, Vec3d>> s = i == 0 ? info.in : info.near;
                    s.removeIf((t) -> t.getLeft().hasSameConnectors(con));
                    if (s.isEmpty())
                        map.remove(p);
                }
                if (info.near.isEmpty() && info.in.isEmpty())
                    map.remove(p);
            }
        }
    };
    raytraceAlongCatenaryRelative(con, (p) -> {
        handle.accept(p.getLeft(), mapForDim);
        return false;
    }, (p) -> handle.accept(p.getLeft(), mapForDim), vecStart, vecEnd);

    IImmersiveConnectable iic = toIIC(con.end, world);
    if (iic != null) {
        iic.removeCable(con);
        back.ifPresent(iic::removeCable);
    }
    iic = toIIC(con.start, world);
    if (iic != null) {
        iic.removeCable(con);
        back.ifPresent(iic::removeCable);
    }

    if (world.isBlockLoaded(con.start))
        world.addBlockEvent(con.start, world.getBlockState(con.start).getBlock(), -1, 0);
    if (world.isBlockLoaded(con.end))
        world.addBlockEvent(con.end, world.getBlockState(con.end).getBlock(), -1, 0);

    IESaveData.setDirty(dim);
}

From source file:com.act.biointerpretation.networkanalysis.MetabolismNetwork.java

/**
 * Trace the pathway back from the given startNode for up to numSteps steps, and return the subgraph of all
 * precursors found.  This is intended to supply explanatory pathways for the input node.
 *
 * @param startNode The node to explain.
 * @param numSteps The number of steps back from the node to search.
 * @return A report representing the precursors of the given starting metabolite.
 *///from ww  w . j  a  v a2 s .co m
public PrecursorReport getPrecursorReport(NetworkNode startNode, int numSteps) {
    if (numSteps <= 0) {
        throw new IllegalArgumentException("Precursor graph is only well-defined for numSteps > 0");
    }

    MetabolismNetwork subgraph = new MetabolismNetwork();
    Map<NetworkNode, Integer> levelMap = new HashMap<>();
    Set<NetworkNode> frontier = new HashSet<>();
    frontier.add(startNode);
    levelMap.put(startNode, 0);

    for (MutableInt l = new MutableInt(1); l.toInteger() <= numSteps; l.increment()) {
        // Get edges leading into the derivative frontier
        List<NetworkEdge> edges = frontier.stream().flatMap(n -> n.getInEdges().stream())
                .collect(Collectors.toList());
        // Add all of the nodes adjacent to the edges, and the edges themselves, to the subgraph
        edges.forEach(e -> this.getSubstrates(e).forEach(subgraph::addNode));
        edges.forEach(e -> this.getProducts(e).forEach(subgraph::addNode));
        edges.forEach(subgraph::addEdge);
        // Calculate new frontier, excluding already-labeled nodes to avoid cycles
        frontier = edges.stream().flatMap(e -> this.getSubstrates(e).stream()).collect(Collectors.toSet());
        frontier.removeIf(levelMap::containsKey);
        // Label remaining nodes with appropriate level.
        frontier.forEach(n -> levelMap.put(n, l.toInteger()));
    }

    return new PrecursorReport(startNode.getMetabolite(), subgraph, levelMap);
}

From source file:com.net2plan.libraries.GraphUtils.java

/** Returns the K minimum cost service chains between two nodes (summing costs of links and resources traversed), traversing a given set of resource types, satisfying some user-defined constraints.
 * If only <i>n</i> shortest path are found (n&lt;K), those are returned. If none is found an empty list is returned. 
 * The subpaths (the set of links between two resources, or the first(last) resource and the origin (destination) node, are constrained to be loopless 
 * (the algorithm uses Yen's scheme for subpaths enumeration).
 * @param links The set of links which can be used for the chain
 * @param originNode The origin node of the chain
 * @param destinationNode The destination node of the chain (could be the same as the origin node)
 * @param sequenceOfResourceTypesToTraverse the types of the sequence of resources to traverse
 * @param linkCost the cost of each link (if null, all links have cost one), all numbers must be strictly positive
 * @param resourceCost a map with the cost of each resource (if null, all resources have cost zero). A resources with Double.MAX_VALUE cost cannot be traversed (as if it was not there). All costs must be nonnegative. If a resource is not present in the map, its cost is zero.  
 * @param K The maximum number of service chains to return (less than K may be returned if there are no different paths).
 * @param maxCostServiceChain Service chains with a cost higher than this are not enumerated
 * @param maxLengthInKmPerSubpath The maximum length in km in each subpath. Service chains not satisfying this are not enumerated
 * @param maxNumHopsPerSubpath The maximum number of traversed links in each subpath. Service chains not satisfying this are not enumerated
 * @param maxPropDelayInMsPerSubpath The propagation delay summing the links in each subpath. Service chains not satisfying this are not enumerated
 * @param cacheSubpathLists A map which associated to node pairs, the k-shortest paths (only considering links) already computed to be used. 
 * The algorithm will add new entries here for those pairs of nodes for which no per-computed values exist, and that are needed in the algorithm 
 * (e.g. for origin node to all nodes of the first resource type, nodes of the first resource type to the second...). If null, then no entries are 
 * precomputed AND also no new entries are returned.   
 * @return the (at most) K minimum cost service chains.
 *///from   w  w w.  jav  a2 s.c  o  m
public static List<Pair<List<NetworkElement>, Double>> getKMinimumCostServiceChains(List<Link> links,
        Node originNode, Node destinationNode, List<String> sequenceOfResourceTypesToTraverse,
        DoubleMatrix1D linkCost, Map<Resource, Double> resourceCost, int K, double maxCostServiceChain,
        double maxLengthInKmPerSubpath, int maxNumHopsPerSubpath, double maxPropDelayInMsPerSubpath,
        Map<Pair<Node, Node>, List<Pair<List<Link>, Double>>> cacheSubpathLists) {
    if (maxLengthInKmPerSubpath <= 0)
        maxLengthInKmPerSubpath = Double.MAX_VALUE;
    if (maxNumHopsPerSubpath <= 0)
        maxNumHopsPerSubpath = Integer.MAX_VALUE;
    if (maxPropDelayInMsPerSubpath <= 0)
        maxPropDelayInMsPerSubpath = Double.MAX_VALUE;
    if (maxCostServiceChain < 0)
        maxCostServiceChain = Double.MAX_VALUE;
    final int E = links.size();
    if (E == 0)
        return new LinkedList<Pair<List<NetworkElement>, Double>>();
    final NetPlan netPlan = links.get(0).getNetPlan();
    if (linkCost == null)
        linkCost = DoubleFactory1D.dense.make(E, 1.0);
    if (linkCost.size() != E)
        throw new Net2PlanException("Wrong size of cost array");
    if (linkCost.getMinLocation()[0] <= 0)
        throw new Net2PlanException("All link costs must be strictly positive");
    if (resourceCost != null)
        for (Double val : resourceCost.values())
            if (val < 0)
                throw new Net2PlanException("All resource costs must be non-negative");

    /* initialize the link cost map */
    Map<Link, Double> linkCostMap = new HashMap<Link, Double>();
    for (int cont = 0; cont < E; cont++)
        linkCostMap.put(links.get(cont), linkCost.get(cont));

    /* initialize the nodes per phase. One element per resource type to traverse, plus one for the last node  */
    List<Set<Node>> nodesPerPhase = new ArrayList<Set<Node>>();
    for (String resourceType : sequenceOfResourceTypesToTraverse) {
        Set<Resource> resourcesNotInfiniteCostThisType = netPlan.getResources(resourceType);
        if (resourceCost != null)
            resourcesNotInfiniteCostThisType.removeIf(e -> resourceCost.get(e) == Double.MAX_VALUE);
        if (resourcesNotInfiniteCostThisType.isEmpty())
            return new LinkedList<Pair<List<NetworkElement>, Double>>();
        final Set<Node> nodesWithResourcesNotInfiniteCostThisType = resourcesNotInfiniteCostThisType.stream()
                .map(e -> e.getHostNode()).collect(Collectors.toCollection(HashSet::new));
        nodesPerPhase.add(nodesWithResourcesNotInfiniteCostThisType);
    }
    nodesPerPhase.add(Collections.singleton(destinationNode));

    /* initialize the path lists. This includes (n,n) pairs with one path of empty seq links and zero cost */
    if (cacheSubpathLists == null)
        cacheSubpathLists = new HashMap<Pair<Node, Node>, List<Pair<List<Link>, Double>>>();
    for (int contPhase = 0; contPhase < nodesPerPhase.size(); contPhase++) {
        final Set<Node> outputNodes = nodesPerPhase.get(contPhase);
        final Set<Node> inputNodes = contPhase == 0 ? Collections.singleton(originNode)
                : nodesPerPhase.get(contPhase - 1);
        for (Node nIn : inputNodes)
            for (Node nOut : outputNodes)
                if (!cacheSubpathLists.containsKey(Pair.of(nIn, nOut)))
                    if (nIn != nOut) {
                        List<List<Link>> kPaths = getKLooplessShortestPaths(netPlan.getNodes(), links, nIn,
                                nOut, linkCostMap, K, maxLengthInKmPerSubpath, maxNumHopsPerSubpath,
                                maxPropDelayInMsPerSubpath, -1, -1, -1);
                        List<Pair<List<Link>, Double>> pathsInfo = new ArrayList<Pair<List<Link>, Double>>();
                        double previousCost = 0;
                        for (List<Link> path : kPaths) {
                            final double thisCost = path.stream().mapToDouble(e -> linkCostMap.get(e)).sum();
                            if (previousCost > thisCost + 0.001)
                                throw new RuntimeException(
                                        "thisCost: " + thisCost + ", previousCost: " + previousCost + ", Bad");
                            if (thisCost > maxCostServiceChain)
                                break; // the maximum cost is exceeded, do not add this as subpath
                            pathsInfo.add(Pair.of(path, thisCost));
                            previousCost = thisCost;
                        }
                        cacheSubpathLists.put(Pair.of(nIn, nOut), pathsInfo);
                    } else
                        cacheSubpathLists.put(Pair.of(nIn, nIn),
                                Collections.singletonList(Pair.of(new LinkedList<Link>(), 0.0)));
    }

    /* Start the main loop */

    /* Initialize the SCs per out node, with those from origin node, to each node with resources of the first type (or end node if this is not a SC) */
    Map<Node, List<Pair<List<NetworkElement>, Double>>> outNodeToKSCsMap = new HashMap<Node, List<Pair<List<NetworkElement>, Double>>>();
    for (Node outNode : nodesPerPhase.get(0)) {
        List<Pair<List<NetworkElement>, Double>> thisFirstStageNodeSCs = new ArrayList<Pair<List<NetworkElement>, Double>>();
        for (Pair<List<Link>, Double> path : cacheSubpathLists.get(Pair.of(originNode, outNode)))
            if (path.getSecond() <= maxCostServiceChain)
                thisFirstStageNodeSCs
                        .add(Pair.of(new LinkedList<NetworkElement>(path.getFirst()), path.getSecond()));
        outNodeToKSCsMap.put(outNode, thisFirstStageNodeSCs);
    }

    final Comparator<Pair<List<NetworkElement>, Double>> scComparator = new Comparator<Pair<List<NetworkElement>, Double>>() {
        public int compare(Pair<List<NetworkElement>, Double> t1, Pair<List<NetworkElement>, Double> t2) {
            return Double.compare(t1.getSecond(), t2.getSecond());
        }
    };

    for (int nextPhase = 1; nextPhase < nodesPerPhase.size(); nextPhase++) {
        final Set<Node> thisPhaseNodes = nodesPerPhase.get(nextPhase - 1);
        final Set<Node> nextPhaseNodes = nodesPerPhase.get(nextPhase);
        final String intermediateNodeResourceType = sequenceOfResourceTypesToTraverse.get(nextPhase - 1);
        Map<Node, List<Pair<List<NetworkElement>, Double>>> new_outNodeToKSCsMap = new HashMap<Node, List<Pair<List<NetworkElement>, Double>>>();
        for (Node newOutNode : nextPhaseNodes) {
            List<Pair<List<NetworkElement>, Double>> kSCsToThisOutNode = new ArrayList<Pair<List<NetworkElement>, Double>>();
            for (Node intermediateNode : thisPhaseNodes) {
                for (Pair<List<NetworkElement>, Double> scOriginToIntermediateInfo : outNodeToKSCsMap
                        .get(intermediateNode)) {
                    final List<NetworkElement> scOriginToIntermediate = scOriginToIntermediateInfo.getFirst();
                    final double scOriginToIntermediateCost = scOriginToIntermediateInfo.getSecond();
                    for (Pair<List<Link>, Double> scIntermediateToOutInfo : cacheSubpathLists
                            .get(Pair.of(intermediateNode, newOutNode))) {
                        final List<NetworkElement> scIntermediateToOut = (List<NetworkElement>) (List<?>) scIntermediateToOutInfo
                                .getFirst();
                        final double scIntermediateToOutCost = scIntermediateToOutInfo.getSecond();
                        if (scOriginToIntermediateCost + scIntermediateToOutCost > maxCostServiceChain)
                            break; // do not add this SC, and no more interm->out paths: all are worse
                        if (kSCsToThisOutNode.size() == K)
                            if (kSCsToThisOutNode.get(K - 1).getSecond() <= scOriginToIntermediateCost
                                    + scIntermediateToOutCost)
                                break; // do not add this SC (already full), and no more interm->out paths: all are worse
                        /* Add as many concatenated SCs as resources here, but do not exceed maximum size k of total list. Resource costs may not be ordered  */
                        for (Resource intermediateResource : intermediateNode
                                .getResources(intermediateNodeResourceType)) {
                            final Double intermediateResourceCost = resourceCost == null ? 0.0
                                    : resourceCost.get(intermediateResource);
                            if (intermediateResourceCost == Double.MAX_VALUE)
                                continue; // resources with infinite cost cannot be used
                            final double totalSCCost = scOriginToIntermediateCost + scIntermediateToOutCost
                                    + ((intermediateResourceCost == null) ? 0.0 : intermediateResourceCost);
                            if (totalSCCost > maxCostServiceChain)
                                continue; // do not add this, but maybe other resources later are cheaper
                            if ((kSCsToThisOutNode.size() == K)
                                    && (totalSCCost > kSCsToThisOutNode.get(K - 1).getSecond()))
                                continue; // do not add this, but maybe other resources later are cheaper 
                            /* Add this SC */
                            List<NetworkElement> newSC = new LinkedList<NetworkElement>(scOriginToIntermediate);
                            newSC.add(intermediateResource);
                            newSC.addAll(scIntermediateToOut);
                            kSCsToThisOutNode
                                    .add(Pair.of(newSC, scOriginToIntermediateCost + scIntermediateToOutCost));
                            /* One SC was added, sort again, and remove the last SCs (higher cost), keep up to K */
                            Collections.sort(kSCsToThisOutNode, scComparator);
                            if (kSCsToThisOutNode.size() > K)
                                kSCsToThisOutNode = kSCsToThisOutNode.subList(0, K);
                        }
                    }
                }
            }
            new_outNodeToKSCsMap.put(newOutNode, kSCsToThisOutNode);
        }
        outNodeToKSCsMap = new_outNodeToKSCsMap;
    }
    if (!outNodeToKSCsMap.keySet().equals(Collections.singleton(destinationNode)))
        throw new RuntimeException("Bad");
    return outNodeToKSCsMap.get(destinationNode);
}