本文整理了Java中java.util.stream.Stream.peek()
方法的一些代码示例,展示了Stream.peek()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stream.peek()
方法的具体详情如下:
包路径:java.util.stream.Stream
类名称:Stream
方法名:peek
[英]Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
This is an intermediate operation.
For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation. If the action modifies shared state, it is responsible for providing the required synchronization.
[中]返回一个由该流的元素组成的流,在从结果流中消耗元素时,对每个元素执行提供的操作。
这是一个intermediate operation。
对于平行流管道,可以在上游操作使元素可用的任何时间和线程中调用该操作。如果操作修改了共享状态,则它负责提供所需的同步。
代码示例来源:origin: stackoverflow.com
List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
.peek(num -> System.out.println("will filter " + num))
.filter(x -> x > 5)
.findFirst()
.get();
System.out.println(a);
代码示例来源:origin: spring-projects/spring-framework
private void updateFilters() {
if (this.filters.isEmpty()) {
return;
}
List<WebFilter> filtersToUse = this.filters.stream()
.peek(filter -> {
if (filter instanceof ForwardedHeaderTransformer && this.forwardedHeaderTransformer == null) {
this.forwardedHeaderTransformer = (ForwardedHeaderTransformer) filter;
}
})
.filter(filter -> !(filter instanceof ForwardedHeaderTransformer))
.collect(Collectors.toList());
this.filters.clear();
this.filters.addAll(filtersToUse);
}
代码示例来源:origin: prestodb/presto
private static Function<Page, Page> enforceLayoutProcessor(List<Symbol> expectedLayout, Map<Symbol, Integer> inputLayout)
{
int[] channels = expectedLayout.stream()
.peek(symbol -> checkArgument(inputLayout.containsKey(symbol), "channel not found for symbol: %s", symbol))
.mapToInt(inputLayout::get)
.toArray();
if (Arrays.equals(channels, range(0, inputLayout.size()).toArray())) {
// this is an identity mapping
return Function.identity();
}
return new PageChannelSelector(channels);
}
代码示例来源:origin: spring-projects/spring-security
private static Map<String, ClientRegistration> createClientRegistrationIdToClientRegistration(Collection<ClientRegistration> registrations) {
Assert.notNull(registrations, "registrations cannot be null");
return Collections.unmodifiableMap(registrations.stream()
.peek(registration -> Assert.notNull(registration, "registrations cannot contain null values"))
.collect(Collectors.toMap(ClientRegistration::getRegistrationId, Function.identity())));
}
代码示例来源:origin: prestodb/presto
@VisibleForTesting
static Estimate calculateDistinctValuesCount(List<HiveColumnStatistics> columnStatistics)
{
return columnStatistics.stream()
.map(MetastoreHiveStatisticsProvider::getDistinctValuesCount)
.filter(OptionalLong::isPresent)
.map(OptionalLong::getAsLong)
.peek(distinctValuesCount -> verify(distinctValuesCount >= 0, "distinctValuesCount must be greater than or equal to zero"))
.max(Long::compare)
.map(Estimate::of)
.orElse(Estimate.unknown());
}
代码示例来源:origin: Vedenin/useful-java-links
private static void testPeek() {
System.out.println();
System.out.println("Test peek start");
Collection<String> collection = Arrays.asList("a1", "a2", "a3", "a1");
// Print debug information for every element
System.out.print("peak1 = ");
List<String> peek = collection.stream().map(String::toUpperCase).peek((e) -> System.out.print(e + ",")).
collect(Collectors.toList());
System.out.println(); // print peak1 = A1,A2,A3,A1,
System.out.println("peek2 = " + peek); // print peek2 = [A1, A2, A3, A1]
Collection<StringBuilder> list = Arrays.asList(new StringBuilder("a1"), new StringBuilder("a2"), new StringBuilder("a3"));
List<StringBuilder> newList = list.stream().peek((p) -> p.append("_new")).collect(Collectors.toList());
System.out.println("newList = " + newList); // print newList = [a1_new, a2_new, a3_new]
}
代码示例来源:origin: hs-web/hsweb-framework
@Override
public Strategy createStrategyIfMatch(Class target, Method method) {
if (switcher.isEmpty()) {
return null;
}
String text = target.getName().concat(".").concat(method.getName());
return switcher.entrySet().stream()
.filter(entry -> antPathMatcher.match(entry.getValue().getExpression(), text))
.peek(entry -> entry.getValue().setId(entry.getKey()))
.map(Map.Entry::getValue)
.findFirst()
.orElse(null);
}
代码示例来源:origin: hs-web/hsweb-framework
@Override
@CacheEvict(allEntries = true)
public List<String> saveOrUpdateColumn(List<DynamicFormColumnEntity> columnEntities) {
Set<String> formId = new HashSet<>();
List<String> columnIds = columnEntities.stream()
.peek(columnEntity -> formId.add(columnEntity.getFormId()))
.map(this::saveOrUpdateColumn)
.collect(Collectors.toList());
formId.forEach(getDao()::incrementVersion);
return columnIds;
}
代码示例来源:origin: SonarSource/sonarqube
public List<DefaultIssue> loadChanges(DbSession dbSession, Collection<DefaultIssue> issues) {
Map<String, List<IssueChangeDto>> changeDtoByIssueKey = dbClient.issueChangeDao()
.selectByIssueKeys(dbSession, issues.stream().map(DefaultIssue::key).collect(toList()))
.stream()
.collect(groupingBy(IssueChangeDto::getIssueKey));
return issues
.stream()
.peek(i -> setChanges(changeDtoByIssueKey, i))
.collect(toList());
}
代码示例来源:origin: SonarSource/sonarqube
private static Optional<QueryBuilder> createQuery(ComponentTextSearchQuery query, ComponentTextSearchFeature[] features, UseCase useCase) {
BoolQueryBuilder generateResults = boolQuery();
AtomicBoolean anyFeatures = new AtomicBoolean();
Arrays.stream(features)
.filter(f -> f.getUseCase() == useCase)
.peek(f -> anyFeatures.set(true))
.flatMap(f -> f.getQueries(query))
.forEach(generateResults::should);
if (anyFeatures.get()) {
return Optional.of(generateResults);
}
return Optional.empty();
}
代码示例来源:origin: prestodb/presto
public ComposableStatsCalculator(List<Rule<?>> rules)
{
this.rulesByRootType = rules.stream()
.peek(rule -> {
checkArgument(rule.getPattern() instanceof TypeOfPattern, "Rule pattern must be TypeOfPattern");
Class<?> expectedClass = ((TypeOfPattern<?>) rule.getPattern()).expectedClass();
checkArgument(!expectedClass.isInterface() && !Modifier.isAbstract(expectedClass.getModifiers()), "Rule must be registered on a concrete class");
})
.collect(toMultimap(
rule -> ((TypeOfPattern<?>) rule.getPattern()).expectedClass(),
rule -> rule,
ArrayListMultimap::create));
}
代码示例来源:origin: SonarSource/sonarqube
private Function<ChangeLogResults, ChangelogWsResponse> buildResponse() {
return result -> Stream.of(ChangelogWsResponse.newBuilder())
.peek(addChanges(result))
.map(ChangelogWsResponse.Builder::build)
.collect(MoreCollectors.toOneElement());
}
代码示例来源:origin: jersey/jersey
@Override
public void init(InjectionManager injectionManager, BootstrapBag bootstrapBag) {
ServerBootstrapBag serverBag = (ServerBootstrapBag) bootstrapBag;
// There are situation in which ComponentProviders are not needed therefore their entire initialization is wrapped
// into a lazy block.
LazyValue<Collection<ComponentProvider>> componentProviders =
Values.lazy((Value<Collection<ComponentProvider>>) () -> getRankedComponentProviders().stream()
.map(RankedProvider::getProvider)
.peek(provider -> provider.initialize(injectionManager))
.collect(Collectors.toList()));
serverBag.setComponentProviders(componentProviders);
}
代码示例来源:origin: jersey/jersey
@Override
public void init(InjectionManager injectionManager, BootstrapBag bootstrapBag) {
ServerBootstrapBag serverBag = (ServerBootstrapBag) bootstrapBag;
// There are situation in which ComponentProviders are not needed therefore their entire initialization is wrapped
// into a lazy block.
LazyValue<Collection<ComponentProvider>> componentProviders =
Values.lazy((Value<Collection<ComponentProvider>>) () -> getRankedComponentProviders().stream()
.map(RankedProvider::getProvider)
.peek(provider -> provider.initialize(injectionManager))
.collect(Collectors.toList()));
serverBag.setComponentProviders(componentProviders);
}
代码示例来源:origin: SonarSource/sonarqube
@Override
public void handle(Request request, Response response) throws Exception {
String eventP = request.mandatoryParam(PARAM_EVENT);
try (DbSession dbSession = dbClient.openSession(false)) {
Stream.of(getEvent(dbSession, eventP))
.peek(checkPermissions())
.peek(checkModifiable())
.forEach(event -> deleteEvent(dbSession, event));
}
response.noContent();
}
代码示例来源:origin: jersey/jersey
@Override
public void init(InjectionManager injectionManager, BootstrapBag bootstrapBag) {
Configuration configuration = bootstrapBag.getConfiguration();
List<AutoDiscoverable> autoDiscoverables = loadImplementations(configuration.getProperties()).stream()
.peek(implClass -> injectionManager.register(Bindings.service(implClass).to(AutoDiscoverable.class)))
.map(injectionManager::createAndInitialize)
.collect(Collectors.toList());
bootstrapBag.setAutoDiscoverables(autoDiscoverables);
}
}
代码示例来源:origin: jersey/jersey
@Override
public void init(InjectionManager injectionManager, BootstrapBag bootstrapBag) {
Configuration configuration = bootstrapBag.getConfiguration();
List<AutoDiscoverable> autoDiscoverables = loadImplementations(configuration.getProperties()).stream()
.peek(implClass -> injectionManager.register(Bindings.service(implClass).to(AutoDiscoverable.class)))
.map(injectionManager::createAndInitialize)
.collect(Collectors.toList());
bootstrapBag.setAutoDiscoverables(autoDiscoverables);
}
}
代码示例来源:origin: SonarSource/sonarqube
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto issueDto = Stream.of(request)
.map(toWsRequest())
.map(loadCommentData(dbSession))
.peek(updateComment(dbSession))
.collect(MoreCollectors.toOneElement())
.getIssueDto();
responseWriter.write(issueDto.getKey(), new SearchResponseData(issueDto), request, response);
}
}
代码示例来源:origin: SonarSource/sonarqube
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto issueDto = Stream.of(request)
.map(loadCommentData(dbSession))
.peek(deleteComment(dbSession))
.collect(MoreCollectors.toOneElement())
.getIssueDto();
responseWriter.write(issueDto.getKey(), new SearchResponseData(issueDto), request, response);
}
}
代码示例来源:origin: SonarSource/sonarqube
protected void assertResultOrder(String query, String... resultsInOrder) {
ComponentDto project = indexProject("key-1", "Quality Product");
List<ComponentDto> files = Arrays.stream(resultsInOrder)
.map(r -> ComponentTesting.newFileDto(project).setName(r))
.peek(f -> f.setUuid(f.uuid() + "_" + f.name().replaceAll("[^a-zA-Z0-9]", "")))
.collect(Collectors.toList());
// index them, but not in the expected order
files.stream()
.sorted(Comparator.comparing(ComponentDto::uuid).reversed())
.forEach(this::index);
assertExactResults(query, files.toArray(new ComponentDto[0]));
}
内容来源于网络,如有侵权,请联系作者删除!