本文整理汇总了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()]));
}
});
}
}
示例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)))));
}
示例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();
}
}
示例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);
}
}
示例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;
}
示例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;
};
}
示例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);
}
示例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();
}
示例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();
}
示例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;
};
}
示例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();
}
示例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();
}
示例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);
}
示例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());
}
}
示例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);
}