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


Java StreamSupport类代码示例

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


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

示例1: addDefaultParams

import java.util.stream.StreamSupport; //导入依赖的package包/类
private void addDefaultParams(SolrQuery solrQuery, SolrEndpointConfiguration config) {
    if(MapUtils.isNotEmpty(config.getDefaults())){
        config.getDefaults().entrySet().stream()
        .filter(e -> StringUtils.isNoneBlank(e.getKey()) && e.getValue() != null)
        .forEach(e -> {
            String param = e.getKey();
            Collection<?> values;
            if(e.getValue() instanceof Collection){
                values = (Collection<?>)e.getValue();
            } else if(e.getValue().getClass().isArray()) {
                 values = Arrays.asList((Object[])e.getValue());
            } else {
                values = Collections.singleton(e.getValue());
            }
            Collection<String> strValues = StreamSupport.stream(values.spliterator(), false)
                    .map(Objects::toString) //convert values to strings
                    .filter(StringUtils::isNoneBlank) //filter blank values
                    .collect(Collectors.toList());
            if(!strValues.isEmpty()){
                solrQuery.add(param, strValues.toArray(new String[strValues.size()]));
            }
        });
    }
}
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:25,代码来源:SolrSearchQueryBuilder.java

示例2: findAll

import java.util.stream.StreamSupport; //导入依赖的package包/类
@GetMapping("/employees")
ResponseEntity<Resources<Resource<Employee>>> findAll() {

	List<Resource<Employee>> employeeResources = StreamSupport.stream(repository.findAll().spliterator(), false)
		.map(employee -> new Resource<>(employee,
			linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel()
				.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, employee.getId())))
				.andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(employee.getId()))),
			linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees")
		))
		.collect(Collectors.toList());

	return ResponseEntity.ok(new Resources<>(employeeResources,
		linkTo(methodOn(EmployeeController.class).findAll()).withSelfRel()
			.andAffordance(afford(methodOn(EmployeeController.class).newEmployee(null)))));
}
 
开发者ID:spring-projects,项目名称:spring-hateoas-examples,代码行数:17,代码来源:EmployeeController.java

示例3: IsOrderListReturned

import java.util.stream.StreamSupport; //导入依赖的package包/类
@Test
public void IsOrderListReturned() {
	try {
		Iterable<Order> orders = orderRepository.findAll();
		assertTrue(StreamSupport.stream(orders.spliterator(), false)
				.noneMatch(o -> (o.getCustomerId() == customer.getCustomerId())));
		ResponseEntity<String> resultEntity = restTemplate.getForEntity(orderURL(), String.class);
		assertTrue(resultEntity.getStatusCode().is2xxSuccessful());
		String orderList = resultEntity.getBody();
		assertFalse(orderList.contains("Eberhard"));
		Order order = new Order(customer.getCustomerId());
		order.addLine(42, item.getItemId());
		orderRepository.save(order);
		orderList = restTemplate.getForObject(orderURL(), String.class);
		assertTrue(orderList.contains("Eberhard"));
	} finally {
		orderRepository.deleteAll();
	}
}
 
开发者ID:ewolff,项目名称:microservice-cloudfoundry,代码行数:20,代码来源:OrderWebIntegrationTest.java

示例4: saveEvents

import java.util.stream.StreamSupport; //导入依赖的package包/类
@Override
public void saveEvents(Iterable<? extends BaseModel> reviews, EventType type) {
    LOGGER.info("Saving list of events");

    try{
        List<Event> eventList = StreamSupport.stream(reviews.spliterator(), false)
            .map(review -> {
                Event platformEvent = new Event();

                platformEvent.setEventType(type);
                platformEvent.setEventTypeCollectionId(review.getId());
                platformEvent.setTimestamp(System.currentTimeMillis());

                return platformEvent;
            }).collect(Collectors.toList());

        eventRepository.save(eventList);
    } catch (Exception e){
        LOGGER.error("Error while saving event", e);
    }
}
 
开发者ID:BBVA,项目名称:mirrorgate,代码行数:22,代码来源:EventServiceImpl.java

示例5: getTask

import java.util.stream.StreamSupport; //导入依赖的package包/类
/**
 * Fork a new compilation task; if possible the compilation context from previous executions is
 * retained (see comments in ReusableContext as to when it's safe to do so); otherwise a brand
 * new context is created.
 */
public JavacTask getTask() {
    if (task == null) {
        ReusableContext context = env.context();
        String opts = options == null ? "" :
                StreamSupport.stream(options.spliterator(), false).collect(Collectors.joining());
        context.clear();
        if (!context.polluted && (context.opts == null || context.opts.equals(opts))) {
            //we can reuse former context
            env.info().ctxReusedCount++;
        } else {
            env.info().ctxDroppedCount++;
            //it's not safe to reuse context - create a new one
            context = env.setContext(new ReusableContext());
        }
        context.opts = opts;
        JavacTask javacTask = ((JavacTool)env.javaCompiler()).getTask(out, env.fileManager(),
                diagsCollector, options, null, sources, context);
        javacTask.setTaskListener(context);
        for (TaskListener l : listeners) {
            javacTask.addTaskListener(l);
        }
        task = javacTask;
    }
    return task;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:31,代码来源:ComboTask.java

示例6: fileCompletions

import java.util.stream.StreamSupport; //导入依赖的package包/类
private CompletionProvider fileCompletions(Predicate<Path> accept) {
    return (code, cursor, anchor) -> {
        int lastSlash = code.lastIndexOf('/');
        String path = code.substring(0, lastSlash + 1);
        String prefix = lastSlash != (-1) ? code.substring(lastSlash + 1) : code;
        Path current = toPathResolvingUserHome(path);
        List<Suggestion> result = new ArrayList<>();
        try (Stream<Path> dir = Files.list(current)) {
            dir.filter(f -> accept.test(f) && f.getFileName().toString().startsWith(prefix))
               .map(f -> new ArgSuggestion(f.getFileName() + (Files.isDirectory(f) ? "/" : "")))
               .forEach(result::add);
        } catch (IOException ex) {
            //ignore...
        }
        if (path.isEmpty()) {
            StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false)
                         .filter(root -> accept.test(root) && root.toString().startsWith(prefix))
                         .map(root -> new ArgSuggestion(root.toString()))
                         .forEach(result::add);
        }
        anchor[0] = path.length();
        return result;
    };
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:25,代码来源:JShellTool.java

示例7: shouldApplyRegisteredServiceMultifactorPolicy

import java.util.stream.StreamSupport; //导入依赖的package包/类
private static boolean shouldApplyRegisteredServiceMultifactorPolicy(final RegisteredServiceMultifactorPolicy policy, final Principal principal) {
    final String attrName = policy.getPrincipalAttributeNameTrigger();
    final String attrValue = policy.getPrincipalAttributeValueToMatch();

    // Principal attribute name and/or value is not defined
    if (!StringUtils.hasText(attrName) || !StringUtils.hasText(attrValue)) {
        return true;
    }

    // no Principal, we should enforce policy
    if (principal == null) {
        return true;
    }

    // check to see if any of the specified attributes match the attrValue pattern
    final Predicate<String> attrValuePredicate = Pattern.compile(attrValue).asPredicate();
    return StreamSupport.stream(ATTR_NAMES.split(attrName).spliterator(), false)
            .map(principal.getAttributes()::get)
            .filter(Objects::nonNull)
            .map(CollectionUtils::toCollection)
            .flatMap(Set::stream)
            .filter(String.class::isInstance)
            .map(String.class::cast)
            .anyMatch(attrValuePredicate);
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:26,代码来源:DefaultMultifactorTriggerSelectionStrategy.java

示例8: getAllImageCompletionSolutions

import java.util.stream.StreamSupport; //导入依赖的package包/类
/**
 * GET  /imageCompletionSolutions -> get all the imageCompletionSolutions.
 */
@RequestMapping(value = "/imageCompletionSolutions",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<ImageCompletionSolution> getAllImageCompletionSolutions(@RequestParam(required = false) String filter) {
    if ("imagecompletionexercise-is-null".equals(filter)) {
        log.debug("REST request to get all ImageCompletionSolutions where imageCompletionExercise is null");
        return StreamSupport
            .stream(imageCompletionSolutionRepository.findAll().spliterator(), false)
            .filter(imageCompletionSolution -> imageCompletionSolution.getImageCompletionExercise() == null)
            .collect(Collectors.toList());
    }

    log.debug("REST request to get all ImageCompletionSolutions");
    return imageCompletionSolutionRepository.findAll();
}
 
开发者ID:GastonMauroDiaz,项目名称:buenojo,代码行数:20,代码来源:ImageCompletionSolutionResource.java

示例9: getAllPhotoLocationBeacons

import java.util.stream.StreamSupport; //导入依赖的package包/类
/**
 * GET  /photoLocationBeacons -> get all the photoLocationBeacons.
 */
@RequestMapping(value = "/photoLocationBeacons",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<PhotoLocationBeacon> getAllPhotoLocationBeacons(@RequestParam(required = false) String filter) {
    if ("exercise-is-null".equals(filter)) {
        log.debug("REST request to get all PhotoLocationBeacons where exercise is null");
        return StreamSupport
            .stream(photoLocationBeaconRepository.findAll().spliterator(), false)
            .filter(photoLocationBeacon -> photoLocationBeacon.getExercise() == null)
            .collect(Collectors.toList());
    }

    log.debug("REST request to get all PhotoLocationBeacons");
    return photoLocationBeaconRepository.findAll();
}
 
开发者ID:GastonMauroDiaz,项目名称:buenojo,代码行数:20,代码来源:PhotoLocationBeaconResource.java

示例10: fileCompletions

import java.util.stream.StreamSupport; //导入依赖的package包/类
private static CompletionProvider fileCompletions(Predicate<Path> accept) {
    return (code, cursor, anchor) -> {
        int lastSlash = code.lastIndexOf('/');
        String path = code.substring(0, lastSlash + 1);
        String prefix = lastSlash != (-1) ? code.substring(lastSlash + 1) : code;
        Path current = toPathResolvingUserHome(path);
        List<Suggestion> result = new ArrayList<>();
        try (Stream<Path> dir = Files.list(current)) {
            dir.filter(f -> accept.test(f) && f.getFileName().toString().startsWith(prefix))
               .map(f -> new ArgSuggestion(f.getFileName() + (Files.isDirectory(f) ? "/" : "")))
               .forEach(result::add);
        } catch (IOException ex) {
            //ignore...
        }
        if (path.isEmpty()) {
            StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false)
                         .filter(root -> Files.exists(root))
                         .filter(root -> accept.test(root) && root.toString().startsWith(prefix))
                         .map(root -> new ArgSuggestion(root.toString()))
                         .forEach(result::add);
        }
        anchor[0] = path.length();
        return result;
    };
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:JShellTool.java

示例11: createOrder

import java.util.stream.StreamSupport; //导入依赖的package包/类
@PostMapping("/orders/new")
HttpEntity<?> createOrder() {

	Iterable<ProductInfo> infos = productInfos.findAll(Sort.by("createdDate").descending());

	ProductInfo info = StreamSupport.stream(infos.spliterator(), false) //
			.findFirst() //
			.orElseThrow(() -> new IllegalStateException("No ProductInfo found!"));

	Order order = Order.newOrder();
	order.add(info, 2);

	orders.save(order.complete());

	return ResponseEntity //
			.created(links.linkForSingleResource(Order.class, order.getId()).toUri()) //
			.build();
}
 
开发者ID:olivergierke,项目名称:sos,代码行数:19,代码来源:OrderController.java

示例12: DefaultSqlConfig

import java.util.stream.StreamSupport; //导入依赖的package包/类
/**
 * コンストラクタ
 *
 * @param connectionSupplier コネクションサプライヤ
 * @param loadPath SQLファイルの読み込みルートパス
 */
private DefaultSqlConfig(final ConnectionSupplier connectionSupplier, final String loadPath) {
	super();
	this.connectionSupplier = connectionSupplier;

	this.sqlManager = new SqlManagerImpl(loadPath);
	this.sqlFilterManager = new SqlFilterManagerImpl();
	this.sqlContextFactory = new SqlContextFactoryImpl();
	this.entityHandler = new DefaultEntityHandler();

	this.dialect = StreamSupport.stream(ServiceLoader.load(Dialect.class).spliterator(), false).filter(d -> d.accept(connectionSupplier)).findFirst().orElseGet(DefaultDialect::new);

	this.sqlAgentFactory = new SqlAgentFactoryImpl(this);

	initialize();
}
 
开发者ID:future-architect,项目名称:uroborosql,代码行数:22,代码来源:DefaultSqlConfig.java

示例13: resolveAttributeReference_WithNonExistingProductReferenceSetAttribute_ShouldNotResolveReferences

import java.util.stream.StreamSupport; //导入依赖的package包/类
@Test
public void resolveAttributeReference_WithNonExistingProductReferenceSetAttribute_ShouldNotResolveReferences() {
    when(productService.fetchCachedProductId(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Optional.empty()));

    final ObjectNode productReference = getProductReferenceWithRandomId();
    final AttributeDraft productReferenceAttribute =
        getProductReferenceSetAttributeDraft("foo", productReference);

    final AttributeDraft resolvedAttributeDraft =
        referenceResolver.resolveAttributeReference(productReferenceAttribute)
                         .toCompletableFuture().join();
    assertThat(resolvedAttributeDraft).isNotNull();
    assertThat(resolvedAttributeDraft.getValue()).isNotNull();

    final Spliterator<JsonNode> attributeReferencesIterator = resolvedAttributeDraft.getValue().spliterator();
    assertThat(attributeReferencesIterator).isNotNull();
    final Set<JsonNode> resolvedSet = StreamSupport.stream(attributeReferencesIterator, false)
                                                   .collect(Collectors.toSet());
    assertThat(resolvedSet).containsExactly(productReference);
}
 
开发者ID:commercetools,项目名称:commercetools-sync-java,代码行数:22,代码来源:VariantReferenceResolverTest.java

示例14: getAllConfigurationsFromDisk

import java.util.stream.StreamSupport; //导入依赖的package包/类
/**
 * Reads the specified configuration directory
 *
 * @param dir Path to config dir
 * @return List of all configuration files
 * @throws IOException on any errors when deserializing {@link Configuration}s
 */
List<String> getAllConfigurationsFromDisk(String dir) throws IOException {
    // nothing to do if configuration not passed
    if (isNull(dir)) {
        logger.warn("Null configuration dir passed, returning empty configuration list");
        return Collections.emptyList();
    }

    try (DirectoryStream<Path> configurationsDirectory = Files.newDirectoryStream(Paths.get(dir))) {
        return StreamSupport.stream(configurationsDirectory.spliterator(), true)
                .filter(ConfigurationIntake::isJsonFile)
                .map(Path::toAbsolutePath)
                .map(Path::toString)
                .collect(Collectors.toList());
    }
}
 
开发者ID:salesforce,项目名称:pyplyn,代码行数:23,代码来源:ConfigurationIntake.java

示例15: lookupPlatformDescription

import java.util.stream.StreamSupport; //导入依赖的package包/类
public static PlatformDescription lookupPlatformDescription(String platformString) {
    int separator = platformString.indexOf(":");
    String platformProviderName =
            separator != (-1) ? platformString.substring(0, separator) : platformString;
    String platformOptions =
            separator != (-1) ? platformString.substring(separator + 1) : "";
    Iterable<PlatformProvider> providers =
            ServiceLoader.load(PlatformProvider.class, Arguments.class.getClassLoader());

    return StreamSupport.stream(providers.spliterator(), false)
                        .filter(provider -> StreamSupport.stream(provider.getSupportedPlatformNames()
                                                                         .spliterator(),
                                                                 false)
                                                         .anyMatch(platformProviderName::equals))
                        .findFirst()
                        .flatMap(provider -> {
                            try {
                                return Optional.of(provider.getPlatform(platformProviderName, platformOptions));
                            } catch (PlatformNotSupported pns) {
                                return Optional.empty();
                            }
                        })
                        .orElse(null);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:PlatformUtils.java


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