当前位置: 首页>>代码示例>>Java>>正文


Java Stream.collect方法代码示例

本文整理汇总了Java中java.util.stream.Stream.collect方法的典型用法代码示例。如果您正苦于以下问题:Java Stream.collect方法的具体用法?Java Stream.collect怎么用?Java Stream.collect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.stream.Stream的用法示例。


在下文中一共展示了Stream.collect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: should_return_an_empty_optional_for_groupingBy_and_maxBy_on_an_empty_stream

import java.util.stream.Stream; //导入方法依赖的package包/类
@Test
public void should_return_an_empty_optional_for_groupingBy_and_maxBy_on_an_empty_stream() {

    // Given
    Stream<String> strings = Stream.empty();

    Collector<String, ?, Optional<Map.Entry<String, Long>>> collector =
            CollectorsUtils.groupingByAndMaxBy(
                    identity(),
                    counting(),
                    Map.Entry.comparingByValue()
            );

    // When
    Optional<Map.Entry<String, Long>> result = strings.collect(collector);

    // Then
    assertThat(result.isPresent()).isFalse();
}
 
开发者ID:JosePaumard,项目名称:collectors-utils,代码行数:20,代码来源:GroupingByAndMaxByTest.java

示例2: should_return_the_max_for_groupingBy_and_maxBy_on_a_non_empty_stream

import java.util.stream.Stream; //导入方法依赖的package包/类
@Test
public void should_return_the_max_for_groupingBy_and_maxBy_on_a_non_empty_stream() {

    // Given
    Stream<String> strings = Stream.of("one", "one", "two", "two", "two");

    Collector<String, ?, Optional<Map.Entry<String, Long>>> collector =
            CollectorsUtils.groupingByAndMaxBy(
                    identity(),
                    counting(),
                    Map.Entry.comparingByValue()
            );

    // When
    Optional<Map.Entry<String, Long>> result = strings.collect(collector);

    // Then
    assertThat(result.isPresent()).isTrue();
    assertThat(result.get()).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("two", 3L));
}
 
开发者ID:JosePaumard,项目名称:collectors-utils,代码行数:21,代码来源:GroupingByAndMaxByTest.java

示例3: getPotentialStates

import java.util.stream.Stream; //导入方法依赖的package包/类
/**
 * Compute all the potentially valid states for a navigate
 * backwards/forwards operation.
 *
 * This means all the states for the given time graph tree element which
 * happen before, or after, the time given timestamp for backwards or
 * forwards operation respectively.
 */
private static List<StateRectangle> getPotentialStates(TimeGraphWidget viewer, long targetTimestamp,
        TimeGraphTreeElement treeElement, boolean forward) {

    Stream<StateRectangle> potentialStates = viewer.getRenderedStateRectangles().stream()
            /* Keep only the intervals of the current tree element */
            .filter(rect -> rect.getStateInterval().getStartEvent().getTreeElement().equals(treeElement));

    if (forward) {
        /*
         * Keep only those intersecting, or happening after, the target
         * timestamp.
         */
        potentialStates = potentialStates.filter(rect -> rect.getStateInterval().getEndEvent().getTimestamp() >= targetTimestamp);
    } else {
        /*
         * Keep only those intersecting, or happening before, the target
         * timestamp.
         */
        potentialStates = potentialStates.filter(rect -> rect.getStateInterval().getStartEvent().getTimestamp() <= targetTimestamp);
    }

    List<StateRectangle> allStates = potentialStates.collect(Collectors.toList());
    return allStates;
}
 
开发者ID:lttng,项目名称:lttng-scope,代码行数:33,代码来源:NavigationModeFollowStateChanges.java

示例4: should_create_the_correct_stream_on_groupingBy_then_n_maxes_with_one_max_and_n_smaller

import java.util.stream.Stream; //导入方法依赖的package包/类
@Test
public void should_create_the_correct_stream_on_groupingBy_then_n_maxes_with_one_max_and_n_smaller() {

    // Given
    Stream<String> strings = Stream.of("one", "two", "two", "three", "three", "four", "four", "four");

    Collector<String, ?, List<Map.Entry<String, Long>>> collector =
            CollectorsUtils.groupingByAndMaxesBy(
                    identity(),
                    counting(),
                    2,
                    Map.Entry.comparingByValue()
            );

    // When
    List<Map.Entry<String, Long>> result = strings.collect(collector);

    // Then
    assertThat(result.size()).isEqualTo(3);
    assertThat(result).containsExactly(
            new AbstractMap.SimpleImmutableEntry<>("four", 3L),
            new AbstractMap.SimpleImmutableEntry<>("three", 2L),
            new AbstractMap.SimpleImmutableEntry<>("two", 2L)
    );
}
 
开发者ID:JosePaumard,项目名称:collectors-utils,代码行数:26,代码来源:GroupingByAndAllMaxTest.java

示例5: inits

import java.util.stream.Stream; //导入方法依赖的package包/类
/**
 * Builds the initial segments of the given <em>finite</em> input stream
 * {@code ts}.
 * For example, if {@code ts = [1, 2, 3]} then {@code init(ts) = [[], [1], 
 * [1,2], [1,2,3]]}.
 * This is a terminal operation.
 * @param <T> any type.
 * @param ts the input stream.
 * @return the initial segments of {@code ts}.
 * @throws NullPointerException if any argument is {@code null}.
 */
public static <T> Stream<Stream<T>> inits(Stream<T> ts) {
    requireNonNull(ts, "ts");
    
    List<T> xs = ts.collect(toList());
    Pair<Stream<T>, Long> seed = new Pair<>(empty(), 0L);
    
    UnaryOperator<Pair<Stream<T>, Long>> nextSegment = k -> {
        long size = k.snd() + 1;
        Stream<T> segment = xs.stream().limit(size);
        return new Pair<>(segment, size);
    };
    return iterate(seed, nextSegment)
           .map(Pair::fst)
           .limit(1 + xs.size());
}
 
开发者ID:openmicroscopy,项目名称:omero-ms-queue,代码行数:27,代码来源:Streams.java

示例6: should_create_the_correct_stream_on_groupingBy_then_all_max_by_value_and_a_comparator_with_one_max

import java.util.stream.Stream; //导入方法依赖的package包/类
@Test @SuppressWarnings("unchecked")
public void should_create_the_correct_stream_on_groupingBy_then_all_max_by_value_and_a_comparator_with_one_max() {

    // Given
    Stream<String> strings = Stream.of("one", "two", "two", "three", "three", "four", "four", "four");

    Collector<String, ?, Set<Map.Entry<String, Long>>> collector =
            CollectorsUtils.groupingByAndAllMaxByValue(
                    Function.<String>identity(),
                    counting(),
                    Comparator.reverseOrder()
            );

    // When
    Set<Map.Entry<String, Long>> result = strings.collect(collector);

    // Then
    assertThat(result.size()).isEqualTo(1);
    assertThat(result).contains(new AbstractMap.SimpleImmutableEntry<>("one", 1L));
}
 
开发者ID:JosePaumard,项目名称:collectors-utils,代码行数:21,代码来源:GroupingByAndAllMaxTest.java

示例7: postProcessSlots

import java.util.stream.Stream; //导入方法依赖的package包/类
private Set<TimeSlot> postProcessSlots(JsonNode node, String date, Exam exam, User user) {
    // Filter out slots that user has a conflicting reservation with
    if (node.isArray()) {
        ArrayNode root = (ArrayNode) node;
        LocalDate searchDate = LocalDate.parse(date, ISODateTimeFormat.dateParser());
        // users reservations starting from now
        List<Reservation> reservations = Ebean.find(Reservation.class)
                .fetch("enrolment.exam")
                .where()
                .eq("user", user)
                .gt("startAt", searchDate.toDate())
                .findList();
        DateTimeFormatter dtf = ISODateTimeFormat.dateTimeParser();
        Stream<JsonNode> stream = StreamSupport.stream(root.spliterator(), false);
        Map<Interval, Optional<Integer>> map = stream.collect(Collectors.toMap(n -> {
                    DateTime start = dtf.parseDateTime(n.get("start").asText());
                    DateTime end = dtf.parseDateTime(n.get("end").asText());
                    return new Interval(start, end);
                }, n -> Optional.of(n.get("availableMachines").asInt()),
                (u, v) -> {
                    throw new IllegalStateException(String.format("Duplicate key %s", u));
                },
                LinkedHashMap::new));
        return handleReservations(map, reservations, exam, null, user);
    }
    return Collections.emptySet();
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:28,代码来源:ExternalCalendarController.java

示例8: findDescendingFirst

import java.util.stream.Stream; //导入方法依赖的package包/类
public Optional<Pattern> findDescendingFirst(final Stream<? extends Candlestick> candlesticks){
    final List<? extends Candlestick> candlestickList = candlesticks.collect(toList());
    return Optional.of(detectGroupOfFivePattern(candlestickList)
                               .orElse(detectGroupOfFourPattern(candlestickList)
                                               .orElse(detectGroupOfThreePattern(candlestickList)
                                                               .orElse(detectGroupOfTwoPattern(candlestickList)
                                                                               .orElse(PatternDto.unknown())))));
}
 
开发者ID:mumukiller,项目名称:stock-patterns-recognition,代码行数:9,代码来源:PatternsDetector.java

示例9: getCenterPoints

import java.util.stream.Stream; //导入方法依赖的package包/类
private List<Point> getCenterPoints(final List<Rectangle> nodesExternalBounds, final List<Node> nodes) {
	final Stream<Point> nodeCenters = nodes.stream().map(n -> n.getCenter());
	final Stream<Point> extBoundCenters = nodesExternalBounds.stream().map(b -> b.getCenter());
	final Stream<Point> allCenters = Stream.concat(nodeCenters, extBoundCenters);
	final List<Point> ctrPoints = allCenters.collect(Collectors.toList());
	return ctrPoints;
}
 
开发者ID:eclipse,项目名称:n4js,代码行数:8,代码来源:Edge.java

示例10: getPlatformMXBeans

import java.util.stream.Stream; //导入方法依赖的package包/类
/**
 * Returns the list of the platform MXBean proxies for
 * forwarding the method calls of the {@code mxbeanInterface}
 * through the given {@code MBeanServerConnection}.
 * The returned list may contain zero, one, or more instances.
 * The number of instances in the returned list is defined
 * in the specification of the given management interface.
 * The order is undefined and there is no guarantee that
 * the list returned is in the same order as previous invocations.
 *
 * @param connection the {@code MBeanServerConnection} to forward to.
 * @param mxbeanInterface a management interface for a platform
 *                        MXBean
 * @param <T> an {@code mxbeanInterface} type parameter
 *
 * @return the list of platform MXBean proxies for
 * forwarding the method calls of the {@code mxbeanInterface}
 * through the given {@code MBeanServerConnection}.
 *
 * @throws IllegalArgumentException if {@code mxbeanInterface}
 * is not a platform management interface.
 *
 * @throws java.io.IOException if a communication problem
 * occurred when accessing the {@code MBeanServerConnection}.
 *
 * @see #newPlatformMXBeanProxy
 * @since 1.7
 */
public static <T extends PlatformManagedObject>
        List<T> getPlatformMXBeans(MBeanServerConnection connection,
                                   Class<T> mxbeanInterface)
    throws java.io.IOException
{
    // Validates at first the specified interface by finding at least one
    // PlatformComponent whose MXBean implements this interface.
    // An interface can be implemented by different MBeans, provided by
    // different platform components.
    PlatformComponent<?> pc = PlatformMBeanFinder.findFirst(mxbeanInterface);
    if (pc == null) {
        throw new IllegalArgumentException(mxbeanInterface.getName()
                + " is not a platform management interface");
    }

    // Collect all names, eliminate duplicates.
    Stream<String> names = Stream.empty();
    for (PlatformComponent<?> p : platformComponents()) {
        names = Stream.concat(names, getProxyNames(p, connection, mxbeanInterface));
    }
    Set<String> objectNames = names.collect(Collectors.toSet());
    if (objectNames.isEmpty()) return Collections.emptyList();

    // Map names on proxies.
    List<T> proxies = new ArrayList<>();
    for (String name : objectNames) {
        proxies.add(newPlatformMXBeanProxy(connection, name, mxbeanInterface));
    }
    return proxies;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:59,代码来源:ManagementFactory.java

示例11: ServerFilter

import java.util.stream.Stream; //导入方法依赖的package包/类
public ServerFilter(Stream<ServerDoc.Role> roles, Stream<ServerDoc.Network> networks, Stream<String> realms, Stream<String> games, Stream<MapDoc.Gamemode> gamemodes) {
    this.roles = roles.collect(Collectors.toImmutableSet());
    this.networks = networks.collect(Collectors.toImmutableSet());
    this.realms = realms.collect(Collectors.toImmutableSet());
    this.games = games.collect(Collectors.toImmutableSet());
    this.gamemodes = gamemodes.collect(Collectors.toImmutableSet());
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:8,代码来源:ServerFilter.java

示例12: testAccessModesOfType

import java.util.stream.Stream; //导入方法依赖的package包/类
static List<TestAccessMode> testAccessModesOfType(TestAccessType... ats) {
    Stream<TestAccessMode> s = Stream.of(TestAccessMode.values());
    for (TestAccessType at : ats) {
        s = s.filter(e -> e.isOfType(at));
    }
    return s.collect(toList());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:8,代码来源:VarHandleBaseTest.java

示例13: assertActiveSnippets

import java.util.stream.Stream; //导入方法依赖的package包/类
private void assertActiveSnippets(Stream<? extends Snippet> snippets, Predicate<Snippet> p, String label) {
    Set<Snippet> active = getActiveKeys().stream()
            .filter(p)
            .collect(Collectors.toSet());
    Set<Snippet> got = snippets
            .collect(Collectors.toSet());
    assertEquals(active, got, label);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:9,代码来源:KullaTesting.java

示例14: restartTest

import java.util.stream.Stream; //导入方法依赖的package包/类
@Test
public void restartTest() {
    List<Indexable> data = wrap(Arrays.asList("data1", "data2", "data3"));
    DataProvider<Indexable> provider = new DataProvider<>(data.iterator());
    Stream<Indexable> stream = provider.getStream();
    List<Indexable> collected = stream.collect(Collectors.toList());
    Assert.assertEquals(collected, data);

    provider = new DataProvider<>(data.iterator());
    stream = provider.getStream();
    collected = stream.collect(Collectors.toList());
    Assert.assertEquals(collected, data);
}
 
开发者ID:Lambda-3,项目名称:Stargraph,代码行数:14,代码来源:DataProviderTest.java

示例15: fromStream

import java.util.stream.Stream; //导入方法依赖的package包/类
public static BRC fromStream(int x, int z, Stream<Vector3i> vectors) {
    return new BRC(x, z, vectors.collect(toImmutableList()));
}
 
开发者ID:kenzierocks,项目名称:HardVox,代码行数:4,代码来源:BaseRegionChunker.java


注:本文中的java.util.stream.Stream.collect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。