Java Code Examples for java.util.Collection#forEach()

The following examples show how to use java.util.Collection#forEach() . 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: Cli.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 6 votes vote down vote up
private void doProductList() {
    Collection<Product> croducts = warehouse.getProducts();
    int maxIdWidth = 0;
    int maxNameWidth = 0;
    int maxPriceWidth = 0;
    for (Product croduct : croducts) {
        int idWidth = String.valueOf(croduct.getId()).length();
        if (idWidth > maxIdWidth) {
            maxIdWidth = idWidth;
        }
        int nameWidth = croduct.getName().length();
        if (nameWidth > maxNameWidth) {
            maxNameWidth = nameWidth;
        }
        int priceWidth = String.valueOf(croduct.getPrice()).length();
        if (priceWidth > maxPriceWidth) {
            maxPriceWidth = priceWidth;
        }
    }
    String fmt = String.format("\t%%%ss\t\t%%%ss\t\t%%%ss%%n", maxIdWidth, maxNameWidth, maxPriceWidth);
    croducts.forEach(p -> System.out.printf(fmt, p.getId(), p.getName(), p.getPrice()));
}
 
Example 2
Source File: NextPollTimeController.java    From hawkbit-examples with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run() {
    final Collection<AbstractSimulatedDevice> devices = repository.getAll();

    devices.forEach(device -> {
        int nextCounter = device.getNextPollCounterSec() - 1;
        if (nextCounter < 0) {
            try {
                pollService.submit(() -> device.poll());
            } catch (final IllegalStateException e) {
                LOGGER.trace("Device could not be polled", e);
            }
            nextCounter = device.getPollDelaySec();
        }

        device.setNextPollCounterSec(nextCounter);
    });
}
 
Example 3
Source File: PositionFinancing.java    From v20-java with MIT License 6 votes vote down vote up
/**
 * Set the Trade Financings
 * <p>
 * The financing paid/collecte for each open Trade within the Position.
 * <p>
 * @param openTradeFinancings the Trade Financings
 * @return {@link PositionFinancing PositionFinancing}
 * @see OpenTradeFinancing
 */
public PositionFinancing setOpenTradeFinancings(Collection<?> openTradeFinancings) {
    ArrayList<OpenTradeFinancing> newOpenTradeFinancings = new ArrayList<OpenTradeFinancing>(openTradeFinancings.size());
    openTradeFinancings.forEach((item) -> {
        if (item instanceof OpenTradeFinancing)
        {
            newOpenTradeFinancings.add((OpenTradeFinancing) item);
        }
        else
        {
            throw new IllegalArgumentException(
                item.getClass().getName() + " cannot be converted to an OpenTradeFinancing"
            );
        }
    });
    this.openTradeFinancings = newOpenTradeFinancings;
    return this;
}
 
Example 4
Source File: MendelianViolationDetector.java    From picard with MIT License 6 votes vote down vote up
/** Flattens out the provided metrics, collates them by "sample", and merges those collations. */
private static  Collection<MendelianViolationMetrics> mergeMetrics(final Collection<Collection<MendelianViolationMetrics>> resultsToReduce) {
    final Collection<MendelianViolationMetrics> allMetrics = new ArrayList<>();
    resultsToReduce.forEach(allMetrics::addAll);

    final Map<String, List<MendelianViolationMetrics>> sampleToMetricsMap =
            allMetrics
                    .stream()
                    .collect(Collectors
                            .groupingBy(m -> String.format("%s|%s|%s|%s", m.FAMILY_ID, m.FATHER, m.MOTHER, m.OFFSPRING)));

    return sampleToMetricsMap
            .values()
            .stream()
            .map(a-> (MendelianViolationMetrics) new MendelianViolationMetrics().merge(a))
            .collect(Collectors.<MendelianViolationMetrics, List<MendelianViolationMetrics>>toCollection(ArrayList<MendelianViolationMetrics>::new));
}
 
Example 5
Source File: TestListenWebSocket.java    From nifi with Apache License 2.0 6 votes vote down vote up
protected Map<Relationship, List<MockFlowFile>> getAllTransferredFlowFiles(final Collection<MockProcessSession> processSessions, final Processor processor) {
    final Map<Relationship, List<MockFlowFile>> flowFiles = new HashMap<>();

    processSessions.forEach(session -> {
        processor.getRelationships().forEach(rel -> {
            List<MockFlowFile> relFlowFiles = flowFiles.get(rel);
            if (relFlowFiles == null) {
                relFlowFiles = new ArrayList<>();
                flowFiles.put(rel, relFlowFiles);
            }
            relFlowFiles.addAll(session.getFlowFilesForRelationship(rel));
        });
    });

    return flowFiles;
}
 
Example 6
Source File: NodeResourceHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Set<String> mapToNodeAspects(Collection<QName> aspects)
{
    Set<String> filteredAspects = new HashSet<>(aspects.size());

    aspects.forEach(q -> {
        if (!nodeAspectFilter.isExcluded(q))
        {
            filteredAspects.add(getQNamePrefixString(q));
        }
    });

    return filteredAspects;
}
 
Example 7
Source File: LambdaProxyHandlerTest.java    From aws-lambda-proxy-java with MIT License 5 votes vote down vote up
@Test
public void corsSupportShouldReturnBadRequestWhenRequiredHeadersNotPresent() {
    LambdaProxyHandler<Configuration> handlerWithCORSSupport = new TestLambdaProxyHandler(true);
    String methodBeingInvestigated = "GET";
    Collection<String> supportedMethods = asList(methodBeingInvestigated, "POST");
    MediaType mediaType1 = MediaType.create("application", "type1");
    MediaType mediaType2 = MediaType.create("application", "type2");
    MediaType mediaType3 = MediaType.create("application", "type3");
    MediaType mediaType4 = MediaType.create("application", "type4");
    List<String> requiredHeaders = Stream.of("header1", "header2")
            .map(Util::randomizeCase)
            .collect(toList());
    SampleMethodHandler sampleMethodHandler = new SampleMethodHandler(requiredHeaders);
    sampleMethodHandler.registerPerAccept(mediaType1, mock(AcceptMapper.class));
    sampleMethodHandler.registerPerAccept(mediaType2, mock(AcceptMapper.class));
    sampleMethodHandler.registerPerAccept(mediaType3, mock(AcceptMapper.class));
    sampleMethodHandler.registerPerContentType(mediaType4, mock(ContentTypeMapper.class));
    supportedMethods.forEach(method -> handlerWithCORSSupport.registerMethodHandler(
            method,
            c -> sampleMethodHandler
    ));
    Map<String, String> headers = new ConcurrentHashMap<>();
    headers.put(ACCESS_CONTROL_REQUEST_METHOD, methodBeingInvestigated);
    headers.put(ACCESS_CONTROL_REQUEST_HEADERS, "");
    headers.put("Content-Type", mediaType4.toString());
    headers.put("Origin", "http://127.0.0.1:8888");
    randomiseKeyValues(headers);
    ApiGatewayProxyRequest request = new ApiGatewayProxyRequestBuilder()
            .withHttpMethod("OPTIONS")
            .withHeaders(headers)
            .withContext(context)
            .build();

    ApiGatewayProxyResponse response = handlerWithCORSSupport.handleRequest(request, context);

    assertThat(response.getStatusCode()).isEqualTo(BAD_REQUEST.getStatusCode());
    assertThat(response.getBody()).contains(String.format("The required header(s) not present: %s", String.join(", ", requiredHeaders.stream().map(String::toLowerCase).collect(toList()))));
}
 
Example 8
Source File: KnownNodesHandlerTest.java    From orion with Apache License 2.0 5 votes vote down vote up
private void addNodesToNetwork(final Collection<KnownNode> nodes) {
  nodes.forEach(node -> {
    try {
      final PublicKey publicKey = PublicKey.fromBytes(Base64.decodeBytes(node.getPublicKey()));
      final URI nodeUri = URI.create(node.getNodeURI());
      networkNodes.addNode(Collections.singletonMap(publicKey.bytes(), nodeUri).entrySet());
    } catch (IllegalArgumentException e) {
      fail(e);
    }
  });
}
 
Example 9
Source File: AttributeStatementHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void addAttributes(AttributeStatementType attributeStatement, ProtocolMapperModel mappingModel,
                                Collection<String> attributeValues) {

    AttributeType attribute = createAttributeType(mappingModel);
    attributeValues.forEach(attribute::addAttributeValue);

    attributeStatement.addAttribute(new AttributeStatementType.ASTChoiceType(attribute));
}
 
Example 10
Source File: UnsecuredNiFiRegistryClientIT.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private void checkExtensionMetadata(Collection<ExtensionMetadata> extensions) {
    extensions.forEach(e -> {
        assertNotNull(e.getBundleInfo());
        assertNotNull(e.getBundleInfo().getBucketId());
        assertNotNull(e.getBundleInfo().getBucketName());
        assertNotNull(e.getBundleInfo().getBundleId());
        assertNotNull(e.getBundleInfo().getGroupId());
        assertNotNull(e.getBundleInfo().getArtifactId());
        assertNotNull(e.getBundleInfo().getVersion());
    });
}
 
Example 11
Source File: VelocityEventManager.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void unregisterListeners(Object plugin) {
  ensurePlugin(plugin);
  Collection<Object> listeners = registeredListenersByPlugin.removeAll(plugin);
  listeners.forEach(methodAdapter::unregister);
  Collection<EventHandler<?>> handlers = registeredHandlersByPlugin.removeAll(plugin);
  handlers.forEach(this::unregisterHandler);
}
 
Example 12
Source File: Table.java    From SpinalTap with Apache License 2.0 5 votes vote down vote up
public static Set<String> getDatabaseNames(Collection<String> canonicalTableNames) {
  Set<String> databaseNames = Sets.newHashSet();

  canonicalTableNames.forEach(
      canonicalTableName -> {
        String databaseName = Splitter.on(':').split(canonicalTableName).iterator().next();
        databaseNames.add(databaseName);
      });

  return databaseNames;
}
 
Example 13
Source File: FlowRuleProgrammableServerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Groups a set of FlowRules by their traffic class ID.
 *
 * @param rules set of NIC rules to install
 * @return a map of traffic class IDs to their set of NIC rules
 */
private Map<String, Set<FlowRule>> groupRules(Collection<FlowRule> rules) {
    Map<String, Set<FlowRule>> rulesPerTc =
        new ConcurrentHashMap<String, Set<FlowRule>>();

    rules.forEach(rule -> {
        if (!(rule instanceof FlowEntry)) {
            NicFlowRule nicRule = null;

            // Only NicFlowRules are accepted
            try {
                nicRule = (NicFlowRule) rule;
            } catch (ClassCastException cEx) {
                log.warn("Skipping flow rule not crafted for NIC: {}", rule);
            }

            if (nicRule != null) {
                String tcId = nicRule.trafficClassId();

                // Create a bucket of flow rules for this traffic class
                if (!rulesPerTc.containsKey(tcId)) {
                    rulesPerTc.put(tcId, Sets.<FlowRule>newConcurrentHashSet());
                }

                Set<FlowRule> tcRuleSet = rulesPerTc.get(tcId);
                tcRuleSet.add(nicRule);
            }
        }
    });

    return rulesPerTc;
}
 
Example 14
Source File: HttpRequestPrinter.java    From Bastion with GNU General Public License v3.0 5 votes vote down vote up
private void writeHeaders(URL url, Collection<ApiHeader> headers, Writer writer, BasicLineFormatter formatter) throws IOException {
    writer.append(BasicLineFormatter.formatHeader(new BasicHeader("Host", url.getHost()), formatter)).append("\r\n");
    headers.forEach(apiHeader -> {
        try {
            writer.append(BasicLineFormatter.formatHeader(new BasicHeader(apiHeader.getName(), apiHeader.getValue()), formatter)).append("\r\n");
        } catch (IOException exception) {
            throw new IllegalStateException(exception);
        }
    });
}
 
Example 15
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private Collection mergeAll(Collection entities) {
	List merged = new ArrayList();
	entities.forEach(ent->merged.add(getHibernateTemplate().merge(ent)));
	return merged;
}
 
Example 16
Source File: Tracks.java    From osgi.iot.contest.sdk with Apache License 2.0 4 votes vote down vote up
private void index(Collection<? extends Segment> segments) {
	segments.forEach(segment -> this.segments.put(segment.id, segment));
}
 
Example 17
Source File: ShowNodeCpuUsageCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
private void printCpuUsage(Collection<NodeCpuUsage> cpuList) {
    cpuList.forEach(cpu -> print("%s", cpu));
}
 
Example 18
Source File: Checks.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Contract("null, _ -> fail")
public static <T extends CharSequence> void noneBlank(final Collection<T> argument, final String name)
{
    notNull(argument, name);
    argument.forEach(it -> notBlank(it, name));
}
 
Example 19
Source File: UaNode.java    From ua-server-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public synchronized void addReferences(Collection<Reference> c) {
    c.forEach(this::addReference);
}
 
Example 20
Source File: CardinalityEstimationTraversal.java    From rheem with Apache License 2.0 4 votes vote down vote up
/**
 * Triggers the {@link #dependentActivations} and puts newly activated {@link Activator}s onto the
 * {@code activatorQueue}.
 */
private void processDependentActivations(Collection<Activation> activations, Queue<Activator> activatorQueue) {
    // Otherwise, we update/activate the dependent estimators.
    activations.forEach(activation -> activation.fire(activatorQueue));
}