Java Code Examples for java.util.List.forEach()

The following are Jave code examples for showing how to use forEach() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Hydrograph   File: ExternalOperationExpressionUtil.java   Source Code and License Vote up 6 votes
private void loadExpressionOutputFieldToMappingSheetRow(List<FilterProperties> outputList, ExpressionOutputFields expressionOutputFields,
		List<FilterProperties> combinedOutputList, List<GridRow> mappingSheetRowSchemaFields) {
	mappingSheetRowSchemaFields.clear();
	if(expressionOutputFields!=null && expressionOutputFields.getField()!=null){
			FilterProperties filterProperties=new FilterProperties();
			filterProperties.setPropertyname(expressionOutputFields.getField().getName());
				if(!outputList.isEmpty()){
					if(!outputList.contains(filterProperties)){
						outputList.forEach(expressionOutputField->expressionOutputField.setPropertyname(filterProperties.getPropertyname()));
						mappingSheetRowSchemaFields.add(SchemaFieldUtil.INSTANCE.getBasicSchemaGridRow(expressionOutputFields.getField()));
					}else{
						mappingSheetRowSchemaFields.add(SchemaFieldUtil.INSTANCE.getBasicSchemaGridRow(expressionOutputFields.getField()));
					}
				}else{
					outputList.add(filterProperties);
					combinedOutputList.add(filterProperties);
					mappingSheetRowSchemaFields.add(SchemaFieldUtil.INSTANCE.getBasicSchemaGridRow(expressionOutputFields.getField()));
				}
	}
}
 
Example 2
Project: mobileAutomation   File: TestCaseDocs.java   Source Code and License Vote up 6 votes
public void run(List<String> suitePackages) {
	String jarPath = Paths.get(System.getProperty("user.dir") + "/mat.jar")
			.toString();

	List<String> availableTestCases = ClassUtils.getClassesNamesInPackage(
			jarPath, suitePackages);

	//TODO - sort test cases alphabetically 
	availableTestCases.forEach(
			c -> {
				final String[] items = c.split("\\.");
				if (items.length>1){
					System.out.println(items[items.length-1]);
				}
			});
}
 
Example 3
Project: emojava   File: Generator.java   Source Code and License Vote up 6 votes
private static void writeCsv(final String targetName, final LocalDate releaseDate, final List<CodepointCsvRow> emojis) throws IOException {
    try (FileWriter fw = new FileWriter(targetName)) {
        writeCsvRow(fw, "# release date = " + releaseDate.toString());
        writeCsvRow(fw, "# headers = code(s), raw, name, type, properties");
        emojis.forEach(a -> {
            try {
                writeCsvRow(
                        fw,
                        Arrays.stream(a.getCodes()).collect(Collectors.joining(" ")),
                        a.getRaw(),
                        a.getName(),
                        a.getType(),
                        Arrays.stream(a.getFeatures()).collect(Collectors.joining("; "))
                );
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        });
    }
}
 
Example 4
Project: hub-fortify-ssc-integration-service   File: VulnerabilityUtil.java   Source Code and License Vote up 6 votes
/**
 * It will be used to remove the duplicate vulnerabilities in the list
 *
 * @param vulnerabilities
 * @return
 */
public static List<Vulnerability> removeDuplicates(List<Vulnerability> vulnerabilities) {
    Map<String, Vulnerability> uniqueKeys = new HashMap<>();
    // Iterate the vulnerabilities to remove the duplicates
    vulnerabilities.forEach(vulnerability -> {
        // The unique vulnerability will be the combination of Component name and version, Channel version and
        // Vulnerability Id
        String uniqueKey = vulnerability.getComponentName() + "~" + vulnerability.getVersion() + "~" + vulnerability.getChannelVersionOriginId() + "~"
                + vulnerability.getVulnerabilityId();

        // If the vulnerability is present in multiple project, then assign the project name and version name to
        // Multiple projects and Multiple versions respectively
        if (uniqueKeys.containsKey(uniqueKey)) {
            vulnerability = new Vulnerability("Multiple projects", "Multiple versions", vulnerability.getProjectId(), vulnerability.getVersionId(),
                    vulnerability.getChannelVersionId(), vulnerability.getComponentName(), vulnerability.getVersion(),
                    vulnerability.getChannelVersionOrigin(), vulnerability.getChannelVersionOriginId(), vulnerability.getChannelVersionOriginName(),
                    vulnerability.getVulnerabilityId(), vulnerability.getDescription(), vulnerability.getPublishedOn(), vulnerability.getUpdatedOn(),
                    vulnerability.getBaseScore(), vulnerability.getExploitability(), vulnerability.getImpact(), vulnerability.getVulnerabilitySource(),
                    vulnerability.getHubVulnerabilityUrl(), vulnerability.getRemediationStatus(), vulnerability.getRemediationTargetDate(),
                    vulnerability.getRemediationActualDate(), vulnerability.getRemediationComment(), vulnerability.getUrl(), vulnerability.getSeverity(),
                    vulnerability.getScanDate());
        }
        uniqueKeys.put(uniqueKey, vulnerability);
    });
    return new ArrayList<>(uniqueKeys.values());
}
 
Example 5
Project: Lagerta   File: ReadTransactionsUnitTest.java   Source Code and License Vote up 5 votes
@Test(dataProvider = DUPLICATES_PRUNING_PROVIDER)
public void checkDuplicatesPruning(
    List<Runnable> happenedActions,
    Set<UUID> lostReaders,
    Set<Long> inProgress,
    Set<Long> expectedInProgress,
    Set<UUID> expectedLostReaders,
    List<ReaderTxScope> expectedReadTxs
) {
    Mockito.doReturn(CommittedTransactions.INITIAL_READY_COMMIT_ID).when(COMMITTED).getLastDenseCommit();
    happenedActions.forEach(Runnable::run);
    read.scheduleDuplicatesPruning();
    read.pruneCommitted(COMMITTED, heartbeats, lostReaders, inProgress);

    assertEquals(expectedInProgress, inProgress);
    assertEquals(expectedLostReaders, lostReaders);

    Iterator<ReaderTxScope> it = read.iterator();

    for (ReaderTxScope scope : expectedReadTxs) {
        ReaderTxScope actualScope = it.next();

        assertEquals(actualScope.getReaderId(), scope.getReaderId());
        assertEquals(actualScope.getTransactionId(), scope.getTransactionId());
        assertEquals(actualScope.isOrphan(), scope.isOrphan());
    }
}
 
Example 6
Project: theskeleton   File: SocialConnectionService.java   Source Code and License Vote up 5 votes
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
	List<SocialConnectionEntity> socialConnections = connectionRepository.findByUserIdOrderByRankAsc(userId);
	MultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>();
	socialConnections.forEach(socialConnection -> {
		Connection<?> connection = connectionMapper.mapRow(socialConnection);
		String providerId = connection.getKey().getProviderId();
		connections.add(providerId, connection);
	});
	return connections;
}
 
Example 7
Project: RedisClusterManager   File: QueryService.java   Source Code and License Vote up 5 votes
public Object get(String cluster, String key) throws Exception {
	List<D_RedisClusterNode> nodes = clusterNodeService.getAllClusterNodes(cluster);
	Set<HostAndPort> masters = new HashSet<HostAndPort>();
	nodes.forEach(node->{
		masters.add(new HostAndPort(node.getHost(), node.getPort()));
	});
	Object value = null;
	JedisCluster jedis = new JedisCluster(masters);
	try {
		String type = jedis.type(key);
		switch (type) {
		case "string":
			value = jedis.get(key);
			break;
		case "list":
			value = jedis.lrange(key, 0, -1);
			break;
		case "set":
			value = jedis.smembers(key);
			break;
		case "zset":
			value = jedis.zrange(key, 0, -1);
			break;
		case "hash":
			value = jedis.hgetAll(key);
			break;
		default:
			break;
		}
	} finally {
		jedis.close();
	}
	return value;
}
 
Example 8
Project: stvs   File: Z3Solver.java   Source Code and License Vote up 5 votes
/**
 * Creates {@link SpecificationRow SpecificationRows} from raw rows.
 *
 * @param validIoVariables variables that might appear in the specification
 * @param durations list of duration for each row
 * @param rawRows Mapping from cycle number x variable name to cell expression as string
 * @return list of specification rows
 */
private static List<SpecificationRow<ConcreteCell>> buildSpecificationRows(
    List<ValidIoVariable> validIoVariables, List<ConcreteDuration> durations,
    Map<Integer, Map<String, String>> rawRows) {
  List<SpecificationRow<ConcreteCell>> specificationRows = new ArrayList<>();
  durations.forEach(
      duration -> buildSpecificationRow(validIoVariables, rawRows, specificationRows, duration));
  return specificationRows;
}
 
Example 9
Project: Hydrograph   File: FieldFormatUtils.java   Source Code and License Vote up 5 votes
public static List<FieldFormat> getFormatList(List<hydrograph.engine.jaxb.ofexcel.FieldFormat.Field> list) {
    List<FieldFormat> fieldFormats = new ArrayList<>();
    list.forEach(element -> {
        FieldFormat f = new FieldFormat();
        f.setName(element.getName());
        if (element.getCopyOfFiled() != null)
            f.setProperty(FieldFormatUtils.setPropertyFromCopyOfFiled(list, element.getCopyOfFiled().getFieldName()));
        else
            f.setProperty(FieldFormatUtils.setProperties(element.getProperty()));
        fieldFormats.add(f);
    });
    return fieldFormats;
}
 
Example 10
Project: comms-router   File: AnswerStrategyWithCallback.java   Source Code and License Vote up 5 votes
private String respondByTransitionToRegularTask(TaskDto task) {
  LOGGER.debug("respondByTransitionToRegularTask");

  AttributeGroupDto taskContext = new AttributeGroupDto();
  taskContext.put(KEY_KIND, new StringAttributeValueDto("regular"));

  boolean updateTaskContextResult = updateTaskContext(task.getRef(), taskContext);
  if (false == updateTaskContextResult) {
    respondWithErrorTalkNcco();
  }

  try {
    String convName = attributeGroupDtogetString(KEY_CONV_NAME, task.getUserContext());
    List<Ncco> list = nccoFactory.nccoListWithAnswerFromCustomerForRegularTask(
        MESSAGE_REGULAR_TASK_GREETING, convName, getMusicOnHoldUrl());

    NccoResponseBuilder builder = new NccoResponseBuilder();
    list.forEach(ncco -> {
      builder.appendNcco(ncco);
    });

    NccoResponse nccoResponse = builder.getValue();
    return nccoResponse.toJson();
  } catch (Exception e) {
    LOGGER.error("respondByTransitionToRegularTask: {}", e.getMessage());
  }

  return respondWithErrorTalkNcco();
}
 
Example 11
Project: elements-of-programming-interviews-solutions   File: QueueWithStacksTest.java   Source Code and License Vote up 5 votes
private void test(int size) {
    final QueueWithStacks queue = new QueueWithStacks();
    List<Integer> integers = StreamUtil.sequence(size);
    integers.forEach(
            i -> queue.enqueue(i)
    );
    integers.forEach(
            i -> assertEquals(i,queue.dequeue())
    );
}
 
Example 12
Project: ReqMan   File: RenderManager.java   Source Code and License Vote up 5 votes
private static final String renderGroupNameList(List<Group> list) {
    StringBuilder sb = new StringBuilder();
    list.forEach(g -> {
        sb.append(g.getName());
        sb.append(", ");
    });
    sb.deleteCharAt(sb.length() - 1); // remove last spcae
    sb.deleteCharAt(sb.length() - 1); // remove last comma
    return sb.toString();
}
 
Example 13
Project: jmonkeybuilder   File: NodeTreeNode.java   Source Code and License Vote up 5 votes
@Override
public @NotNull Array<TreeNode<?>> getChildren(@NotNull final NodeTree<?> nodeTree) {

    final Array<TreeNode<?>> result = ArrayFactory.newArray(TreeNode.class);
    final List<Spatial> children = getSpatials();
    children.forEach(spatial -> result.add(FACTORY_REGISTRY.createFor(spatial)));
    result.addAll(super.getChildren(nodeTree));

    return result;
}
 
Example 14
Project: canal-elasticsearch   File: ElasticsearchServiceImpl.java   Source Code and License Vote up 5 votes
@Override
public void deleteById(String index, String type, List<ElasticsearchMetadata.EsRowData> esRowDataList) {
    esRowDataList.forEach(esRowData -> {
        String idColumn = esRowData.getIdColumn();
        String id = (String) esRowData.getRowData().get(idColumn);
        transportClient.prepareDelete(index, type, id).get();
        logger.info("Delete into elasticsearch  ====> {} ", index + "." + type + "." + id);

    });

}
 
Example 15
Project: drift   File: TestDriftClient.java   Source Code and License Vote up 5 votes
@SafeVarargs
private final void assertNoTExceptionInvocation(
        ResultsSupplier resultsSupplier,
        Collection<Supplier<InvokeRequest>> targets,
        TestingMethodInvocationStatsFactory statsFactory,
        List<TestingExceptionClassifier> classifiers,
        Client client,
        Optional<String> qualifier,
        Throwable testException,
        Class<? extends Throwable>... expectedWrapperTypes)
{
    String name = "exception-" + testException.getClass().getName();

    TestingMethodInvocationStat stat = statsFactory.getStat("clientService", qualifier, "testNoTException");
    stat.clear();
    resultsSupplier.setFailedResult(testException);
    try {
        invocationId++;
        client.testNoTException(invocationId, name);
        fail("Expected exception");
    }
    catch (Throwable e) {
        assertExceptionChain(e, testException, expectedWrapperTypes);
        classifiers.forEach(classifier -> classifier.assertLastException(testException));
    }
    verifyMethodInvocation(targets, "testNoTException", invocationId, name);
    stat.assertFailure(0);
}
 
Example 16
Project: jtsgen   File: TSDGenerator.java   Source Code and License Vote up 4 votes
private void outputTypes(TSModuleInfo module, int ident, List<TSType> types, PrintWriter out) {
    if (types.isEmpty()) return;

    TSTypeVisitor tsTypeVisitor = creatTypeVisitor(module, out);
    types.forEach(x -> x.accept(tsTypeVisitor, ident));
}
 
Example 17
Project: cf-mta-deploy-service   File: CreateOrUpdateServicesStep.java   Source Code and License Vote up 4 votes
private Map<String, CloudService> getServicesMap(List<CloudService> services) {
    Map<String, CloudService> servicesMap = new HashMap<>(services.size());
    services.forEach(service -> servicesMap.put(service.getName(), service));
    return servicesMap;
}
 
Example 18
Project: exelixi-am   File: Structure.java   Source Code and License Vote up 4 votes
default void actorDecls(List<GlobalEntityDecl> entityDecls) {
    entityDecls.forEach(backend().structure()::actorDecl);
}
 
Example 19
Project: hybris-integration-intellij-idea-plugin   File: FlexibleSearchHttpClient.java   Source Code and License Vote up 4 votes
public @NotNull
    HybrisHttpResult execute(final String content) {
//        HTTPRequestManager httpRequestManager = HTTPRequestManager.getInstance();
//        List<NameValuePair> scriptParameter = new ArrayList<NameValuePair>();
//        if(isHybrisVersion5OrAbove()) {
//            scriptParameter.add(new BasicNameValuePair("scriptType", "flexibleSearch"));
//            scriptParameter.add(new BasicNameValuePair("commit", "false"));
//        }
//        scriptParameter.add(new BasicNameValuePair("flexibleSearchQuery", script));
//        scriptParameter.add(new BasicNameValuePair("user", username));
//        scriptParameter.add(new BasicNameValuePair("locale", localeISOCode));
//        scriptParameter.add(new BasicNameValuePair("maxCount", maxCount));
//        scriptParameter.add(new BasicNameValuePair("sqlQuery", ""));
//        return httpRequestManager.doPostRequestWithCookie(serverURL + (isHybrisVersion5OrAbove() ? HYBRIS_5_CONSOLE_EXECUTE_URL : FLEXSEARCH_CONSOLE_EXECUTE_URL), jSessionID, scriptParameter);

        final List<BasicNameValuePair> params = asList(
            new BasicNameValuePair("scriptType", "flexibleSearch"),
            new BasicNameValuePair("commit", "false"),
            new BasicNameValuePair("flexibleSearchQuery", content),
            new BasicNameValuePair("sqlQuery", ""),
            new BasicNameValuePair("maxCount", "100")
//            new BasicNameValuePair("locale", localeISOCode)
        );
        HybrisHttpResult.HybrisHttpResultBuilder resultBuilder = HybrisHttpResult.HybrisHttpResultBuilder.createResult();
        final String actionUrl = hybrisHttpClient.hostUrl() + "/console/flexsearch/execute";
        try {
            final String sessionId = hybrisHttpClient.sessionId();
            final HttpResponse response = hybrisHttpClient.post(actionUrl, sessionId, params);
            resultBuilder = resultBuilder.httpCode(response.getStatusLine().getStatusCode());
            final Document document = parse(response.getEntity().getContent(), CharEncoding.UTF_8, "");

            final HashMap json = gsonParser.fromJson(document.getElementsByTag("body").text(), HashMap.class);
            if (json.get("exception") != null) {
                return HybrisHttpResult.HybrisHttpResultBuilder.createResult()
                                                               .errorMessage(json.get("exception").toString())
                                                               .detailMessage(json.get("exception").toString()).build();
            } else {
                TableBuilder tableBuilder = new TableBuilder();

                final List<String> headers = (List<String>) json.get("headers");
                final List<List<String>> resultList = (List<List<String>>) json.get("resultList");

                tableBuilder.addRow(headers.toArray(new String[]{}));
                resultList.forEach(row -> tableBuilder.addRow(row.toArray(new String[]{})));

                return resultBuilder.output(tableBuilder.toString()).build();
            }
        } catch (final IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            return resultBuilder.errorMessage(e.getMessage() + ' ' + actionUrl).httpCode(SC_BAD_REQUEST).build();
        }
    }
 
Example 20
Project: athena   File: InterfaceConfig.java   Source Code and License Vote up 3 votes
private ArrayNode putIps(List<InterfaceIpAddress> intfIpAddresses) {
    ArrayNode ipArray = mapper.createArrayNode();

    intfIpAddresses.forEach(i -> ipArray.add(i.toString()));

    return ipArray;
}