當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。