Example usage for java.util List stream

List of usage examples for java.util List stream

Introduction

In this page you can find the example usage for java.util List stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:alfio.controller.AdminController.java

private static void downloadTicketsCSV(String eventName, String fileName, String[] header, Principal principal,
        HttpServletResponse response, EventManager eventManager, Function<Ticket, String[]> ticketMapper)
        throws IOException {
    Validate.isTrue(StringUtils.isNotBlank(eventName), "Event name is not valid");
    List<Ticket> tickets = eventManager.findAllConfirmedTickets(eventName, principal.getName());
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-" + fileName + ".csv");
    try (ServletOutputStream out = response.getOutputStream()) {
        for (int marker : BOM_MARKERS) {//UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897
            out.write(marker);// ww w . java 2 s  .c o m
        }
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out));
        writer.writeNext(header);
        tickets.stream().map(ticketMapper).forEach(writer::writeNext);
        writer.flush();
        out.flush();
    }
}

From source file:cognition.common.utils.StringTools.java

/**
 *
 * @param text The source text.//  www  .ja  v a  2  s  .  c  om
 * @param search The text to be searched in {@code text}.
 * @param threshold The threshold value between 0.0 - 1.0.
 * @return A list of MatchingWindow objects.
 */
public static List<MatchingWindow> getMatchingWindowsAboveThreshold(String text, String search,
        double threshold) {
    if (StringUtils.isBlank(text)) {
        return new ArrayList<>();
    }
    if (StringUtils.isBlank(search)) {
        return new ArrayList<>();
    }
    String[] addressWords = search.split(" ");
    int bagSize = addressWords.length;
    String[] textWords = text.split(" ");
    int textWordCount = textWords.length;
    List<MatchingWindow> windows = new ArrayList<>();
    for (int i = 0; i < textWordCount; i++) {
        MatchingWindow window = takeBag(textWords, i, bagSize);
        window.setScoreAccordingTo(addressWords);
        window.setMatchingText(text.substring(window.getBegin(), window.getEnd()));
        windows.add(window);
    }

    Collections.sort(windows);
    windows = windows.stream().filter(window -> window.isScoreAboveThreshold(threshold))
            .collect(Collectors.toList());

    return windows;
}

From source file:com.khartec.waltz.jobs.sample.MeasurablesGenerator.java

private static void generateRegions(DSLContext dsl) throws IOException {
    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/regions.csv"));

    System.out.println("Deleting existing Regions & Countries ...");
    int deletedCount = dsl.deleteFrom(MEASURABLE)
            .where(MEASURABLE.MEASURABLE_CATEGORY_ID
                    .in(DSL.select(MEASURABLE_CATEGORY.ID).from(MEASURABLE_CATEGORY)
                            .where(MEASURABLE_CATEGORY.EXTERNAL_ID.eq(REGION_CATEGORY_EXTERNAL_ID))))
            .and(MEASURABLE.PROVENANCE.eq("demo")).execute();
    System.out.println("Deleted: " + deletedCount + " existing Regions & Countries");

    Map<String, Map<String, Set<String>>> regionHierarchy = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ","))
            .filter(cells -> notEmpty(cells[0]) && notEmpty(cells[6]) && notEmpty(cells[5]))
            .map(cells -> Tuple.tuple(cells[0], cells[6], cells[5]))
            .collect(groupingBy(t -> t.v3, groupingBy(t -> t.v2, mapping(t -> t.v1, toSet()))));

    final long measurableCategoryId = dsl.select(MEASURABLE_CATEGORY.ID).from(MEASURABLE_CATEGORY)
            .where(MEASURABLE_CATEGORY.EXTERNAL_ID.eq(REGION_CATEGORY_EXTERNAL_ID)).fetchAny().value1();

    AtomicInteger insertCount = new AtomicInteger(0);
    regionHierarchy.forEach((region, subRegionMap) -> {
        final long regionId = dsl.insertInto(MEASURABLE)
                .set(createRegion(null, region, measurableCategoryId, false)).returning(MEASURABLE.ID)
                .fetchOne().getId();/*from  www.j a v  a2s.c om*/
        insertCount.incrementAndGet();

        subRegionMap.forEach((subRegion, countries) -> {
            final long subRegionId = dsl.insertInto(MEASURABLE)
                    .set(createRegion(regionId, subRegion, measurableCategoryId, true)).returning(MEASURABLE.ID)
                    .fetchOne().getId();
            insertCount.incrementAndGet();

            insertCount.addAndGet(dsl.batchInsert(countries.stream()
                    .map(country -> createRegion(subRegionId, country, measurableCategoryId, true))
                    .collect(toList())).execute().length);
        });
    });

    System.out.println("Inserted: " + insertCount + " Regions & Countries");
}

From source file:com.thinkbiganalytics.metadata.jpa.support.GenericQueryDslFilter.java

/**
 * convert a passed in filter string to a list of criteria objects
 *
 * @param filterString a filter, <column><operator><value> Example: jobinstance.name==jobName,jobExcutionId>=200.  that will search for all jobs named 'jobName' and jobExecutionId >= 200
 * @return a list of criteria objects//from   ww w  .jav a2s. co m
 */
public static List<SearchCriteria> parseFilterString(String filterString) {
    List<SearchCriteria> searchCriterias = new ArrayList<>();
    if (StringUtils.isNotBlank(filterString)) {

        //first match and split on , for various filters
        String[] filterConditions = filterString.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)");
        List<String> filterConditionsList = Arrays.asList(filterConditions);

        //Pattern used to match the <column><operator><value>
        String validOperatorsRegEx = operators.keySet().stream().map(key -> key)
                .collect(Collectors.joining("|"));
        Pattern columnOperatorValuePattern = Pattern.compile("(.*)(" + validOperatorsRegEx + ")(.*)");

        filterConditionsList.stream().forEach(filter -> {
            Matcher matcher = columnOperatorValuePattern.matcher(filter);
            while (matcher.find()) {
                String field = matcher.group(1);
                String operator = matcher.group(2);
                String value = matcher.group(3);
                searchCriterias.add(new SearchCriteria(field, operator, value));
            }
        });
    }
    return searchCriterias;
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

public static boolean isScaleInputValid(final List<Integer> segmentsToSeal,
        final List<AbstractMap.SimpleEntry<Double, Double>> newRanges, final byte[] segmentTable) {
    boolean newRangesPredicate = newRanges.stream()
            .noneMatch(x -> x.getKey() >= x.getValue() && x.getKey() >= 0 && x.getValue() > 0);

    List<AbstractMap.SimpleEntry<Double, Double>> oldRanges = segmentsToSeal.stream()
            .map(segment -> SegmentRecord.readRecord(segmentTable, segment)
                    .map(x -> new AbstractMap.SimpleEntry<>(x.getRoutingKeyStart(), x.getRoutingKeyEnd())))
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());

    return newRangesPredicate && reduce(oldRanges).equals(reduce(newRanges));
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java

private static CloseableHttpClient recordHttpClientForMultipleJsonAndStatusCodeResponse(
        List<String> jsonResponses, List<Integer> statusCodes) throws IOException {
    CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class);

    List<HttpEntity> httpEntities = jsonResponses.stream()
            .map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList());
    when(httpResponseMock.getEntity()).thenReturn(httpEntities.get(0),
            httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1]));

    List<StatusLine> statusLines = statusCodes.stream().map(ConfluenceRestClientTest::recordStatusLine)
            .collect(toList());/*from  w  w  w . j a v  a  2s.c  o m*/
    when(httpResponseMock.getStatusLine()).thenReturn(statusLines.get(0),
            statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1]));

    CloseableHttpClient httpClientMock = anyCloseableHttpClient();
    when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock);

    return httpClientMock;
}

From source file:com.strider.datadefender.DataDefender.java

/**
 * Returns the list of unparsed arguments as a list of table names by
 * transforming the strings to lower case.
 *
 * This guarantees table names to be in lower case, so functions comparing
 * can use contains() with a lower case name.
 *
 * If tables names are not supplied via command line, then will search the property file
 * for space separated list of table names.
 *
 * @param tableNames//from   w  w  w.j a  va 2 s  .  c om
 * @param appProperties application property file
 * @param dbProperties database property file
 * @return The list of table names
 */
public static Set<String> getTableNames(final List<String> tableNames, final Properties dbProperties) {
    List<String> tableNameList = new ArrayList<String>(Arrays.asList(new String[tableNames.size()]));

    Collections.copy(tableNameList, tableNames);

    if (tableNameList.isEmpty()) {
        final String tableStr = dbProperties.getProperty("include-tables");

        if (tableStr != null) {
            tableNameList = Arrays.asList(tableStr.split(","));
            LOG.debug("Adding tables from property file.");
        }
    }

    final Set<String> tables = tableNameList.stream().map(s -> s.toLowerCase(Locale.ENGLISH))
            .collect(Collectors.toSet());

    LOG.info("Tables: " + Arrays.toString(tables.toArray()));

    return tables;
}

From source file:uk.ac.ebi.ep.data.service.EnzymePortalService.java

private static Predicate enzymesByNamePrefixes(List<String> namePrefixes) {
    QUniprotEntry enzyme = QUniprotEntry.uniprotEntry;
    StringExpression idPrefix = enzyme.relatedProteinsId.namePrefix;
    BooleanBuilder builder = new BooleanBuilder();
    namePrefixes.stream().forEach(prefix -> {

        builder.or(idPrefix.equalsIgnoreCase(prefix));

    });//from  ww  w.  j  a v a 2 s.  co m
    return builder;
}

From source file:JacksonJacksumTest.java

@BeforeClass
public static void setUpClass() throws IOException {

    List<HashResultHolder> list = new ObjectMapper().readValue(
            JacksonJacksumTest.class.getResourceAsStream("/jacksum_image.json"),
            new TypeReference<List<HashResultHolder>>() {
            });/*from www  .ja  va  2  s.  co m*/

    IMAGE_FILE_RESULTS = list.stream()
            .collect(Collectors.toMap(HashResultHolder::getAlgorithm, Function.identity()));

    /*Map<String, String> map = JacksumAPI.getAvailableAlgorithms();
     map.keySet().stream()
     .forEach(cannonicalName -> System.out.println(cannonicalName.toUpperCase()+"(\""+map.get(cannonicalName)+"\",\""+cannonicalName+"\", \"alias\"),"));
     */
    /*JacksumAPI.getAvailableAlgorithms().keySet().stream()
     .forEach(name -> System.out.println("@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS)  public String "+name+"FileAlt() {return this.getFileHashValue(this.getChecksum(\""+name+"\", true), FILE);}"));
     */
    //        IMAGE_FILE_RESULTS.keySet().stream().forEach(str -> System.out.println("@Test public void test_" + str + "(){this.individualTest(\"" + str + "\");}"));
    list = new ObjectMapper().readValue(JacksonJacksumTest.class.getResourceAsStream("/jacksum_text.json"),
            new TypeReference<List<HashResultHolder>>() {
            });

    TEXT_FILE_RESULTS = list.stream()
            .collect(Collectors.toMap(HashResultHolder::getAlgorithm, Function.identity()));

    list = new ObjectMapper().readValue(JacksonJacksumTest.class.getResourceAsStream("/jacksum_string.json"),
            new TypeReference<List<HashResultHolder>>() {
            });

    STRING_RESULTS = list.stream()
            .collect(Collectors.toMap(HashResultHolder::getAlgorithm, Function.identity()));

}

From source file:de.micromata.genome.jpa.metainf.MetaInfoUtils.java

/**
 * To entity meta data.//w  w w  . jav  a2  s  . c om
 *
 * @param mt the mt
 * @return the entity metadata
 */
private static EntityMetadata toEntityMetaData(ManagedType<?> mt) {
    EntityMetadataBean ret = new EntityMetadataBean();
    ret.setJavaType(mt.getJavaType());
    if (mt instanceof EntityType) {
        EntityType ift = (EntityType) mt;
        ret.setDatabaseName(ift.getName());
    }
    // TODO RK delete propDesc
    List<PropertyDescriptor> propDescs = Arrays.asList(PropertyUtils.getPropertyDescriptors(ret.getJavaType()));
    Set<?> attr = mt.getAttributes();
    for (Object oa : attr) {

        Attribute<?, ?> at = (Attribute<?, ?>) oa;
        Optional<PropertyDescriptor> pdo = propDescs.stream().filter((el) -> el.getName().equals(at.getName()))
                .findFirst();
        ColumnMetadata colm = getColumnMetaData(ret, mt.getJavaType(), at, pdo);
        if (colm != null) {
            ret.getColumns().put(colm.getName(), colm);
        }
    }
    /// EntityType.getName() is not correct.
    Table[] tabs = mt.getJavaType().getAnnotationsByType(Table.class);
    if (tabs != null && tabs.length > 0) {
        for (Table tab : tabs) {
            if (StringUtils.isNotBlank(tab.name()) == true) {
                ret.setDatabaseName(tab.name());
                break;
            }
        }
    }
    return ret;
}