Example usage for java.util.stream StreamSupport stream

List of usage examples for java.util.stream StreamSupport stream

Introduction

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

Prototype

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) 

Source Link

Document

Creates a new sequential or parallel Stream from a Spliterator .

Usage

From source file:Main.java

/**
 * Convert a sequence of elements to the list.
 *
 * @param <I> Type of objects for input collection
 * @param <O> Type of objects for output collection
 * @param iterable The sequence of elements to convert. If the input
 *     sequence is empty, then the resulting collection will be empty
 * @param transformer The conversion function. If the transfer function is
 *     not set, the resulting collection will be empty
 * @return Reformed collection of input elements
 *///from  w  w  w .ja  v  a  2 s.c om
public static <I, O> List<O> transformWithoutNull(final Iterable<I> iterable,
        final Function<I, O> transformer) {
    return StreamSupport
            .stream(Optional.ofNullable(iterable).orElse(Collections.<I>emptySet()).spliterator(), false)
            .map(Optional.ofNullable(transformer).orElse(i -> null)).filter(Objects::nonNull)
            .collect(Collectors.toList());
}

From source file:Main.java

public static <T> Set<T> union(Iterable<Set<T>> elements) {
    return StreamSupport.stream(elements.spliterator(), true).flatMap(Set::stream).collect(toSet());
}

From source file:org.obiba.mica.web.model.GitCommitInfoDtos.java

@NotNull
public List<Mica.GitCommitInfoDto> asDto(Iterable<CommitInfo> commitInfos) {
    return StreamSupport.stream(commitInfos.spliterator(), false).map(this::asDto).collect(Collectors.toList());
}

From source file:mtsar.api.csv.WorkerCSV.java

public static Iterator<Worker> parse(Stage stage, CSVParser csv) {
    final Set<String> header = csv.getHeaderMap().keySet();
    checkArgument(!Sets.intersection(header, Sets.newHashSet(HEADER)).isEmpty(), "Unknown CSV header: %s",
            String.join(",", header));

    return StreamSupport.stream(csv.spliterator(), false).map(row -> {
        final String id = row.isSet("id") ? row.get("id") : null;
        final String[] tags = row.isSet("tags") && !StringUtils.isEmpty(row.get("tags"))
                ? row.get("tags").split("\\|")
                : new String[0];
        final String datetime = row.isSet("datetime") ? row.get("datetime") : null;

        return new Worker.Builder().setId(StringUtils.isEmpty(id) ? null : Integer.valueOf(id))
                .setStage(stage.getId()).addAllTags(Arrays.asList(tags))
                .setDateTime(new Timestamp(StringUtils.isEmpty(datetime) ? System.currentTimeMillis()
                        : Long.parseLong(datetime) * 1000L))
                .build();/*w w w.  ja v  a2 s . com*/
    }).iterator();
}

From source file:org.hawkular.services.rest.test.InventoryHelper.java

static List<ExtendedInventoryStructure> extractStructuresFromResponse(JsonNode response) {
    return StreamSupport.stream(response.spliterator(), true).map(node -> node.get("data"))
            .map(InventoryHelper::rebuildFromChunks).filter(Optional::isPresent).map(Optional::get)
            .collect(Collectors.toList());
}

From source file:cn.edu.zjnu.acm.judge.mapper.BestSubmissionsBuilder.java

public static String bestSubmissions(@Param("problemId") long problemId, @Param("pageable") Pageable pageable) {
    Set<String> dejaVu = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    Sort sort = Optional.ofNullable(pageable.getSort()).map(s -> s.and(DEFAULT_SORT)).orElse(DEFAULT_SORT);
    Sort.Order[] orders = StreamSupport.stream(sort.spliterator(), false)
            .filter(order -> ALLOW_COLUMNS.contains(order.getProperty()) && dejaVu.add(order.getProperty()))
            .toArray(Sort.Order[]::new);
    final int length = orders.length;
    log.debug("{}", Arrays.asList(orders));

    StringBuilder sb = new StringBuilder(
            "select " + SubmissionMapper.LIST_COLUMNS + " from solution s where problem_id=").append(problemId)
                    .append(" and score=100 ");
    for (int i = length - 1; i >= 0; --i) {
        sb.append("and(user_id");
        for (int j = 0; j <= i; ++j) {
            sb.append(',').append(orders[j].getProperty());
        }/*from ww w .j  a  v  a 2s .  c o  m*/
        sb.append(")in(select user_id");
        for (int j = 0; j < i; ++j) {
            sb.append(',').append(orders[j].getProperty());
        }
        sb.append(',').append(orders[i].isAscending() ? "min" : "max").append("(")
                .append(orders[i].getProperty()).append(")").append(orders[i].getProperty())
                .append(" from solution where problem_id=").append(problemId).append(" and score=100 ");
    }
    for (int i = 0; i < length; ++i) {
        sb.append("group by user_id)");
    }
    if (length > 0) {
        sb.append(" order by ");
        for (int i = 0; i < length; ++i) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(orders[i].getProperty());
            if (!orders[i].isAscending()) {
                sb.append(" desc");
            }
        }
    }
    return sb.append(" limit ").append(pageable.getOffset()).append(",").append(pageable.getPageSize())
            .toString();
}

From source file:mtsar.api.csv.TaskCSV.java

public static Iterator<Task> parse(Stage stage, CSVParser csv) {
    final Set<String> header = csv.getHeaderMap().keySet();
    checkArgument(!Sets.intersection(header, Sets.newHashSet(HEADER)).isEmpty(), "Unknown CSV header: %s",
            String.join(",", header));

    return StreamSupport.stream(csv.spliterator(), false).map(row -> {
        final String id = row.isSet("id") ? row.get("id") : null;
        final String[] tags = row.isSet("tags") && !StringUtils.isEmpty(row.get("tags"))
                ? row.get("tags").split("\\|")
                : new String[0];
        final String type = row.get("type");
        final String description = row.isSet("description") ? row.get("description") : null;
        final String[] answers = row.isSet("answers") && !StringUtils.isEmpty(row.get("answers"))
                ? row.get("answers").split("\\|")
                : new String[0];
        final String datetime = row.isSet("datetime") ? row.get("datetime") : null;

        return new Task.Builder().setId(StringUtils.isEmpty(id) ? null : Integer.valueOf(id))
                .setStage(stage.getId()).addAllTags(Arrays.asList(tags))
                .setDateTime(new Timestamp(StringUtils.isEmpty(datetime) ? System.currentTimeMillis()
                        : Long.parseLong(datetime) * 1000L))
                .setType(StringUtils.defaultIfEmpty(type, TaskDAO.TASK_TYPE_SINGLE)).setDescription(description)
                .addAllAnswers(Arrays.asList(answers)).build();
    }).iterator();//w ww  .  jav a 2  s. c o m
}

From source file:Main.java

/**
 * Converts an {@link java.util.Iterator} to {@link java.util.stream.Stream}.
 *//*from  w  ww . ja va2  s  .co  m*/
public static <T> Stream<T> iterate(Iterator<? extends T> iterator) {
    int characteristics = Spliterator.ORDERED | Spliterator.IMMUTABLE;
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, characteristics), false);
}

From source file:net.hamnaberg.json.Item.java

public static Item create(Optional<URI> href, Iterable<Property> properties, List<Link> links) {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    href.ifPresent(uri -> node.put("href", uri.toString()));
    if (!Iterables.isEmpty(properties)) {
        node.set("data", StreamSupport.stream(properties.spliterator(), false).map(Extended::asJson)
                .collect(JsonNodeFactory.instance::arrayNode, ArrayNode::add, ArrayNode::addAll));
    }//from   w ww  .j  av a 2  s . co  m
    if (!Iterables.isEmpty(links)) {
        node.set("links", StreamSupport.stream(links.spliterator(), false).map(Extended::asJson)
                .collect(JsonNodeFactory.instance::arrayNode, ArrayNode::add, ArrayNode::addAll));
    }
    return new Item(node);
}

From source file:mtsar.api.csv.AnswerCSV.java

public static Iterator<Answer> parse(Stage stage, CSVParser csv) {
    final Set<String> header = csv.getHeaderMap().keySet();
    checkArgument(!Sets.intersection(header, Sets.newHashSet(HEADER)).isEmpty(), "Unknown CSV header: %s",
            String.join(",", header));

    return StreamSupport.stream(csv.spliterator(), false).map(row -> {
        final String id = row.isSet("id") ? row.get("id") : null;
        final String[] tags = row.isSet("tags") && !StringUtils.isEmpty(row.get("tags"))
                ? row.get("tags").split("\\|")
                : new String[0];
        final String type = row.isSet("type") ? row.get("type") : null;
        final String workerId = row.get("worker_id");
        final String taskId = row.get("task_id");
        final String[] answers = row.isSet("answers") && !StringUtils.isEmpty(row.get("answers"))
                ? row.get("answers").split("\\|")
                : new String[0];
        final String datetime = row.isSet("datetime") ? row.get("datetime") : null;

        return new Answer.Builder().setId(StringUtils.isEmpty(id) ? null : Integer.valueOf(id))
                .setStage(stage.getId()).addAllTags(Arrays.asList(tags))
                .setDateTime(new Timestamp(StringUtils.isEmpty(datetime) ? System.currentTimeMillis()
                        : Long.parseLong(datetime) * 1000L))
                .setType(StringUtils.defaultIfEmpty(type, AnswerDAO.ANSWER_TYPE_DEFAULT))
                .setWorkerId(Integer.valueOf(workerId)).setTaskId(Integer.valueOf(taskId))
                .addAllAnswers(Arrays.asList(answers)).build();
    }).iterator();/*ww  w  . j  a  va 2s .c o m*/
}