本文整理匯總了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();
}
示例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));
}
示例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;
}
示例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)
);
}
示例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());
}
示例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));
}
示例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();
}
示例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())))));
}
示例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;
}
示例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;
}
示例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());
}
示例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());
}
示例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);
}
示例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);
}
示例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()));
}