java.util.stream.StreamSupport Java Examples
The following examples show how to use
java.util.stream.StreamSupport.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TripDurationToAverageTripDuration.java From amazon-kinesis-analytics-taxi-consumer with Apache License 2.0 | 6 votes |
@Override public void apply(Tuple tuple, TimeWindow timeWindow, Iterable<TripDuration> iterable, Collector<AverageTripDuration> collector) { if (Iterables.size(iterable) > 1) { String location = Iterables.get(iterable, 0).pickupGeoHash; String airportCode = Iterables.get(iterable, 0).airportCode; long sumDuration = StreamSupport .stream(iterable.spliterator(), false) .mapToLong(trip -> trip.tripDuration) .sum(); double avgDuration = (double) sumDuration / Iterables.size(iterable); collector.collect(new AverageTripDuration(location, airportCode, sumDuration, avgDuration, timeWindow.getEnd())); } }
Example #2
Source File: ConsoleLogApplicationTests.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
@Test public void contextLoads() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); String val = context.getProperty(SpacedLogbackSystem.KEY_ENABLED); Assert.assertEquals("true", val); Logger logger = context.getLogger("com.baidu"); Assert.assertEquals(Level.DEBUG, logger.getLevel()); logger = context.getLogger("com.baidu.ebiz"); Assert.assertEquals(Level.WARN, logger.getLevel()); logger = context.getLogger("ROOT"); List<Appender<ILoggingEvent>> list = StreamSupport.stream( Spliterators.spliteratorUnknownSize( logger.iteratorForAppenders(), Spliterator.ORDERED), false) .collect(Collectors.toList()); Assert.assertThat(list.size(), Matchers.greaterThan(1)); LoggerFactory.getLogger("com.baidu").info("info for root"); StatusPrinter.print(context); }
Example #3
Source File: CallbacksITBase.java From sdn-rx with Apache License 2.0 | 6 votes |
protected void verifyDatabase(Iterable<ThingWithAssignedId> expectedValues) { List<String> ids = StreamSupport.stream(expectedValues.spliterator(), false) .map(ThingWithAssignedId::getTheId).collect(toList()); List<String> names = StreamSupport.stream(expectedValues.spliterator(), false) .map(ThingWithAssignedId::getName).collect(toList()); try (Session session = driver.session()) { Record record = session .run("MATCH (n:Thing) WHERE n.theId in $ids RETURN COLLECT(n) as things", Values.parameters("ids", ids)) .single(); List<Node> nodes = record.get("things").asList(Value::asNode); assertThat(nodes).extracting(n -> n.get("theId").asString()).containsAll(ids); assertThat(nodes).extracting(n -> n.get("name").asString()) .containsAll(names); } }
Example #4
Source File: IdGeneratorsIT.java From sdn-rx with Apache License 2.0 | 6 votes |
@Test void idGenerationWithNewEntitiesShouldWork(@Autowired ThingWithGeneratedIdRepository repository) { List<ThingWithGeneratedId> things = IntStream.rangeClosed(1, 10) .mapToObj(i -> new ThingWithGeneratedId("name" + i)) .collect(toList()); Iterable<ThingWithGeneratedId> savedThings = repository.saveAll(things); assertThat(savedThings) .hasSize(things.size()) .extracting(ThingWithGeneratedId::getTheId) .allMatch(s -> s.matches("thingWithGeneratedId-\\d+")); Set<String> distinctIds = StreamSupport.stream(savedThings.spliterator(), false) .map(ThingWithGeneratedId::getTheId).collect(toSet()); assertThat(distinctIds).hasSize(things.size()); }
Example #5
Source File: EcsJsonSerializerTest.java From ecs-logging-java with Apache License 2.0 | 6 votes |
@Test void serializeExceptionAsArray() throws IOException { Exception exception = new Exception("foo"); StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.append('{'); EcsJsonSerializer.serializeException(jsonBuilder, exception, true); jsonBuilder.append('}'); System.out.println(jsonBuilder); JsonNode jsonNode = new ObjectMapper().readTree(jsonBuilder.toString()); assertThat(jsonNode.get("error.type").textValue()).isEqualTo(exception.getClass().getName()); assertThat(jsonNode.get("error.message").textValue()).isEqualTo("foo"); StringWriter stringWriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringWriter)); assertThat(StreamSupport.stream(jsonNode.get("error.stack_trace").spliterator(), false) .map(JsonNode::textValue) .collect(Collectors.joining(System.lineSeparator(), "", System.lineSeparator()))) .isEqualTo(stringWriter.toString()); }
Example #6
Source File: Jackson2ObjectMapperBuilderTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // gh-22740 public void registerMultipleModulesWithNullTypeId() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); SimpleModule fooModule = new SimpleModule(); fooModule.addSerializer(new FooSerializer()); SimpleModule barModule = new SimpleModule(); barModule.addSerializer(new BarSerializer()); builder.modulesToInstall(fooModule, barModule); ObjectMapper objectMapper = builder.build(); assertEquals(1, StreamSupport .stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false) .filter(s -> s.findSerializer(null, SimpleType.construct(Foo.class), null) != null) .count()); assertEquals(1, StreamSupport .stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false) .filter(s -> s.findSerializer(null, SimpleType.construct(Bar.class), null) != null) .count()); }
Example #7
Source File: EnvironmentConfigurationLogger.java From kubernetes-crash-course with MIT License | 6 votes |
@SuppressWarnings("rawtypes") @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { final Environment environment = event.getApplicationContext().getEnvironment(); LOGGER.info("====== Environment and configuration ======"); LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles())); final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources(); StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource) .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct() .forEach(prop -> { Object resolved = environment.getProperty(prop, Object.class); if (resolved instanceof String) { LOGGER.info("{} - {}", prop, environment.getProperty(prop)); } else { LOGGER.info("{} - {}", prop, "NON-STRING-VALUE"); } }); LOGGER.debug("==========================================="); }
Example #8
Source File: GoToCmd.java From Wurst7 with GNU General Public License v3.0 | 6 votes |
private BlockPos argsToEntityPos(String name) throws CmdError { LivingEntity entity = StreamSupport .stream(MC.world.getEntities().spliterator(), true) .filter(e -> e instanceof LivingEntity).map(e -> (LivingEntity)e) .filter(e -> !e.removed && e.getHealth() > 0) .filter(e -> e != MC.player) .filter(e -> !(e instanceof FakePlayerEntity)) .filter(e -> name.equalsIgnoreCase(e.getDisplayName().getString())) .min( Comparator.comparingDouble(e -> MC.player.squaredDistanceTo(e))) .orElse(null); if(entity == null) throw new CmdError("Entity \"" + name + "\" could not be found."); return new BlockPos(entity.getPos()); }
Example #9
Source File: GetRatings.java From schedge with MIT License | 6 votes |
/** * Two step process, first given the list of instructors, * find the coressponding rmp-id. Then using the new rmp-id, * query the rating. * E.g: * For professor "Victor Shoup": * 1. We first find the rmp-id on RMP using getLinkAsync * -> rmp-id: 1134872 * 2. We then use the rmp-id to query the rating itself * -> https://www.ratemyprofessors.com/ShowRatings.jsp?tid=1134872; * @param names * @param batchSizeNullable * @return */ public static Stream<Rating> getRatings(Iterator<Instructor> names, Integer batchSizeNullable) { int batchSize = batchSizeNullable != null ? batchSizeNullable : 50; // @Performance what should this number be? // @TODO Change this to actually be correct in terms of types used SimpleBatchedFutureEngine<Instructor, Instructor> instructorResults = new SimpleBatchedFutureEngine<>( names, batchSize, (instructor, __) -> getLinkAsync(instructor)); SimpleBatchedFutureEngine<Instructor, Rating> engine = new SimpleBatchedFutureEngine<>( instructorResults, batchSize, (instructor, __) -> { try { return queryRatingAsync(instructor.name, instructor.id); } catch (Exception e) { throw new RuntimeException(e); } }); return StreamSupport.stream(engine.spliterator(), false) .filter(i -> i != null); }
Example #10
Source File: EnvironmentConfigurationLogger.java From pcf-crash-course-with-spring-boot with MIT License | 6 votes |
@SuppressWarnings("rawtypes") @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { final Environment environment = event.getApplicationContext().getEnvironment(); LOGGER.info("====== Environment and configuration ======"); LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles())); final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources(); StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource) .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct() .forEach(prop -> { LOGGER.info("{}", prop); // Object resolved = environment.getProperty(prop, Object.class); // if (resolved instanceof String) { // LOGGER.info("{}", environment.getProperty(prop)); // } }); LOGGER.info("==========================================="); }
Example #11
Source File: EnvironmentConfigurationLogger.java From pcf-crash-course-with-spring-boot with MIT License | 6 votes |
@SuppressWarnings("rawtypes") @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { final Environment environment = event.getApplicationContext().getEnvironment(); LOGGER.info("====== Environment and configuration ======"); LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles())); final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources(); StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource) .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct() .forEach(prop -> { LOGGER.info("{}", prop); // Object resolved = environment.getProperty(prop, Object.class); // if (resolved instanceof String) { // LOGGER.info("{}", environment.getProperty(prop)); // } }); LOGGER.info("==========================================="); }
Example #12
Source File: EnvironmentConfigurationLogger.java From kubernetes-crash-course with MIT License | 6 votes |
@SuppressWarnings("rawtypes") @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { final Environment environment = event.getApplicationContext().getEnvironment(); LOGGER.info("====== Environment and configuration ======"); LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles())); final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources(); StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource) .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct() .forEach(prop -> { Object resolved = environment.getProperty(prop, Object.class); if (resolved instanceof String) { LOGGER.info("{} - {}", prop, environment.getProperty(prop)); } else { LOGGER.info("{} - {}", prop, "NON-STRING-VALUE"); } }); LOGGER.debug("==========================================="); }
Example #13
Source File: EntityRecordItemListenerNFTTest.java From hedera-mirror-node with Apache License 2.0 | 5 votes |
private void assertEntities() { var expected = expectedEntityNum.toArray(); var actual = StreamSupport.stream(entityRepository.findAll().spliterator(), false) .map(e -> e.getEntityNum()) .toArray(); Arrays.sort(expected); Arrays.sort(actual); assertArrayEquals(expected, actual); }
Example #14
Source File: CharSequence.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Returns a stream of {@code int} zero-extending the {@code char} values * from this sequence. Any char which maps to a <a * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code * point</a> is passed through uninterpreted. * * <p>If the sequence is mutated while the stream is being read, the * result is undefined. * * @return an IntStream of char values from this sequence * @since 1.8 */ public default IntStream chars() { class CharIterator implements PrimitiveIterator.OfInt { int cur = 0; public boolean hasNext() { return cur < length(); } public int nextInt() { if (hasNext()) { return charAt(cur++); } else { throw new NoSuchElementException(); } } @Override public void forEachRemaining(IntConsumer block) { for (; cur < length(); cur++) { block.accept(charAt(cur)); } } } return StreamSupport.intStream(() -> Spliterators.spliterator( new CharIterator(), length(), Spliterator.ORDERED), Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, false); }
Example #15
Source File: CharSequence.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Returns a stream of {@code int} zero-extending the {@code char} values * from this sequence. Any char which maps to a <a * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code * point</a> is passed through uninterpreted. * * <p>If the sequence is mutated while the stream is being read, the * result is undefined. * * @return an IntStream of char values from this sequence * @since 1.8 */ public default IntStream chars() { class CharIterator implements PrimitiveIterator.OfInt { int cur = 0; public boolean hasNext() { return cur < length(); } public int nextInt() { if (hasNext()) { return charAt(cur++); } else { throw new NoSuchElementException(); } } @Override public void forEachRemaining(IntConsumer block) { for (; cur < length(); cur++) { block.accept(charAt(cur)); } } } return StreamSupport.intStream(() -> Spliterators.spliterator( new CharIterator(), length(), Spliterator.ORDERED), Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, false); }
Example #16
Source File: FollowCmd.java From Wurst7 with GNU General Public License v3.0 | 5 votes |
@Override public void call(String[] args) throws CmdException { if(args.length != 1) throw new CmdSyntaxError(); FollowHack followHack = WURST.getHax().followHack; if(followHack.isEnabled()) followHack.setEnabled(false); Entity entity = StreamSupport .stream(MC.world.getEntities().spliterator(), true) .filter(e -> e instanceof LivingEntity) .filter(e -> !e.removed && ((LivingEntity)e).getHealth() > 0) .filter(e -> e != MC.player) .filter(e -> !(e instanceof FakePlayerEntity)) .filter(e -> args[0].equalsIgnoreCase(e.getName().getString())) .min( Comparator.comparingDouble(e -> MC.player.squaredDistanceTo(e))) .orElse(null); if(entity == null) throw new CmdError( "Entity \"" + args[0] + "\" could not be found."); followHack.setEntity(entity); followHack.setEnabled(true); }
Example #17
Source File: DefaultJdbcRepositoryOperations.java From micronaut-data with Apache License 2.0 | 5 votes |
@NonNull @Override public <T> Stream<T> entityStream(@NonNull ResultSet resultSet, @Nullable String prefix, @NonNull Class<T> rootEntity) { ArgumentUtils.requireNonNull("resultSet", resultSet); ArgumentUtils.requireNonNull("rootEntity", rootEntity); TypeMapper<ResultSet, T> mapper = new SqlResultEntityTypeMapper<>(prefix, getEntity(rootEntity), columnNameResultSetReader, jsonCodec); Iterable<T> iterable = () -> new Iterator<T>() { boolean nextCalled = false; @Override public boolean hasNext() { try { if (!nextCalled) { nextCalled = true; return resultSet.next(); } else { return nextCalled; } } catch (SQLException e) { throw new DataAccessException("Error retrieving next JDBC result: " + e.getMessage(), e); } } @Override public T next() { nextCalled = false; return mapper.map(resultSet, rootEntity); } }; return StreamSupport.stream(iterable.spliterator(), false); }
Example #18
Source File: CustomFJPoolTest.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
static int countSplits(ForkJoinPool fjp) throws Exception { // The number of splits will be equivalent to the number of leaf nodes // and will be a power of 2 ForkJoinTask<Integer> fInteger = fjp.submit(() -> { Spliterator<Integer> s = IntStream.range(0, 1024).boxed().parallel().spliterator(); SplitCountingSpliterator<Integer> cs = new SplitCountingSpliterator<>(s); StreamSupport.stream(cs, true).forEach(e -> {}); return cs.splits(); }); return fInteger.get(); }
Example #19
Source File: ReadOnlyKeyValueStoreGrpcClient.java From apicurio-registry with Apache License 2.0 | 5 votes |
@Override public long approximateNumEntries() { StreamObserverSpliterator<io.apicurio.registry.streams.distore.proto.Size> observer = new StreamObserverSpliterator<>(); stub.approximateNumEntries( VoidReq.newBuilder() .setStoreName(storeName) .build(), observer ); return StreamSupport .stream(observer, false) .mapToLong(Size::getSize) .findFirst() .getAsLong(); }
Example #20
Source File: RegionFailoverITCase.java From flink with Apache License 2.0 | 5 votes |
@Override public void initializeState(FunctionInitializationContext context) throws Exception { int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask(); if (context.isRestored()) { restoredState = true; unionListState = context.getOperatorStateStore().getUnionListState(unionStateDescriptor); Set<Integer> actualIndices = StreamSupport.stream(unionListState.get().spliterator(), false).collect(Collectors.toSet()); if (getRuntimeContext().getTaskName().contains(SINGLE_REGION_SOURCE_NAME)) { Assert.assertTrue(CollectionUtils.isEqualCollection(EXPECTED_INDICES_SINGLE_REGION, actualIndices)); } else { Assert.assertTrue(CollectionUtils.isEqualCollection(EXPECTED_INDICES_MULTI_REGION, actualIndices)); } if (indexOfThisSubtask == 0) { listState = context.getOperatorStateStore().getListState(stateDescriptor); Assert.assertTrue("list state should be empty for subtask-0", ((List<Integer>) listState.get()).isEmpty()); } else { listState = context.getOperatorStateStore().getListState(stateDescriptor); Assert.assertTrue("list state should not be empty for subtask-" + indexOfThisSubtask, ((List<Integer>) listState.get()).size() > 0); if (indexOfThisSubtask == NUM_OF_REGIONS - 1) { index = listState.get().iterator().next(); if (index != snapshotIndicesOfSubTask.get(lastCompletedCheckpointId.get())) { throw new RuntimeException("Test failed due to unexpected recovered index: " + index + ", while last completed checkpoint record index: " + snapshotIndicesOfSubTask.get(lastCompletedCheckpointId.get())); } } } } else { unionListState = context.getOperatorStateStore().getUnionListState(unionStateDescriptor); if (indexOfThisSubtask != 0) { listState = context.getOperatorStateStore().getListState(stateDescriptor); } } }
Example #21
Source File: MobEspHack.java From Wurst7 with GNU General Public License v3.0 | 5 votes |
@Override public void onUpdate() { mobs.clear(); Stream<MobEntity> stream = StreamSupport.stream(MC.world.getEntities().spliterator(), false) .filter(e -> e instanceof MobEntity).map(e -> (MobEntity)e) .filter(e -> !e.removed && e.getHealth() > 0); if(filterInvisible.isChecked()) stream = stream.filter(e -> !e.isInvisible()); mobs.addAll(stream.collect(Collectors.toList())); }
Example #22
Source File: TypeMappedAnnotations.java From spring-analysis-note with MIT License | 5 votes |
@Override public <A extends Annotation> Stream<MergedAnnotation<A>> stream(String annotationType) { if (this.annotationFilter == FILTER_ALL) { return Stream.empty(); } return StreamSupport.stream(spliterator(annotationType), false); }
Example #23
Source File: CommandUtils.java From mcspring-boot with MIT License | 5 votes |
private static Stream<String> getSuggestedValues(PositionalParamSpec paramSpec) { Iterable<String> completionCandidates = paramSpec.completionCandidates(); if (completionCandidates != null) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(completionCandidates.iterator(), 0), false); } else { return getSuggestedValues(paramSpec.type()); } }
Example #24
Source File: Utils.java From iroha-java with Apache License 2.0 | 5 votes |
private static Iterable<Transaction> createBatch(Iterable<Transaction> list, BatchType batchType) { final Iterable<String> batchHashes = getBatchHashesHex(list); return StreamSupport.stream(list.spliterator(), false) .map(tx -> tx .makeMutable() .setBatchMeta(batchType, batchHashes) .build() ) .collect(Collectors.toList()); }
Example #25
Source File: SchemaGenerationContextImpl.java From jsonschema-generator with Apache License 2.0 | 5 votes |
/** * Collect the specified value(s) from the given definition's {@link SchemaKeyword#TAG_TYPE} attribute. * * @param definition type definition to extract specified {@link SchemaKeyword#TAG_TYPE} values from * @return extracted {@link SchemaKeyword#TAG_TYPE} – values (may be empty) */ private Set<String> collectAllowedSchemaTypes(ObjectNode definition) { JsonNode declaredTypes = definition.get(this.getKeyword(SchemaKeyword.TAG_TYPE)); final Set<String> allowedSchemaTypes; if (declaredTypes == null) { allowedSchemaTypes = Collections.emptySet(); } else if (declaredTypes.isTextual()) { allowedSchemaTypes = Collections.singleton(declaredTypes.textValue()); } else { allowedSchemaTypes = StreamSupport.stream(declaredTypes.spliterator(), false) .map(JsonNode::textValue) .collect(Collectors.toSet()); } return allowedSchemaTypes; }
Example #26
Source File: PlaceDAOImpl.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public Stream<Place> streamAll() { Context timer = streamAllTimer.time(); Iterator<Row> rows = session.execute(streamAll.bind()).iterator(); Iterator<Place> result = TimingIterator.time( Iterators.transform(rows, (row) -> buildEntity(row)), timer ); Spliterator<Place> stream = Spliterators.spliteratorUnknownSize(result, Spliterator.IMMUTABLE | Spliterator.NONNULL); return StreamSupport.stream(stream, false); }
Example #27
Source File: BitSet.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Returns a stream of indices for which this {@code BitSet} * contains a bit in the set state. The indices are returned * in order, from lowest to highest. The size of the stream * is the number of bits in the set state, equal to the value * returned by the {@link #cardinality()} method. * * <p>The bit set must remain constant during the execution of the * terminal stream operation. Otherwise, the result of the terminal * stream operation is undefined. * * @return a stream of integers representing set indices * @since 1.8 */ public IntStream stream() { class BitSetIterator implements PrimitiveIterator.OfInt { int next = nextSetBit(0); @Override public boolean hasNext() { return next != -1; } @Override public int nextInt() { if (next != -1) { int ret = next; next = nextSetBit(next+1); return ret; } else { throw new NoSuchElementException(); } } } return StreamSupport.intStream( () -> Spliterators.spliterator( new BitSetIterator(), cardinality(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED), Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED, false); }
Example #28
Source File: NonFeeTransferExtractionStrategyImplTest.java From hedera-mirror-node with Apache License 2.0 | 5 votes |
@Test void extractNonFeeTransfersFailedCryptoCreate() { var transactionBody = getCryptoCreateTransactionBody(); var result = extractionStrategy.extractNonFeeTransfers(transactionBody, getFailedTransactionRecord()); assertAll( () -> assertEquals(1, StreamSupport.stream(result.spliterator(), false).count()) , () -> assertResult(createAccountAmounts(payerAccountNum, 0 - initialBalance), result) ); }
Example #29
Source File: BufferedReader.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Returns a {@code Stream}, the elements of which are lines read from * this {@code BufferedReader}. The {@link Stream} is lazily populated, * i.e., read only occurs during the * <a href="../util/stream/package-summary.html#StreamOps">terminal * stream operation</a>. * * <p> The reader must not be operated on during the execution of the * terminal stream operation. Otherwise, the result of the terminal stream * operation is undefined. * * <p> After execution of the terminal stream operation there are no * guarantees that the reader will be at a specific position from which to * read the next character or line. * * <p> If an {@link IOException} is thrown when accessing the underlying * {@code BufferedReader}, it is wrapped in an {@link * UncheckedIOException} which will be thrown from the {@code Stream} * method that caused the read to take place. This method will return a * Stream if invoked on a BufferedReader that is closed. Any operation on * that stream that requires reading from the BufferedReader after it is * closed, will cause an UncheckedIOException to be thrown. * * @return a {@code Stream<String>} providing the lines of text * described by this {@code BufferedReader} * * @since 1.8 */ public Stream<String> lines() { Iterator<String> iter = new Iterator<String>() { String nextLine = null; @Override public boolean hasNext() { if (nextLine != null) { return true; } else { try { nextLine = readLine(); return (nextLine != null); } catch (IOException e) { throw new UncheckedIOException(e); } } } @Override public String next() { if (nextLine != null || hasNext()) { String line = nextLine; nextLine = null; return line; } else { throw new NoSuchElementException(); } } }; return StreamSupport.stream(Spliterators.spliteratorUnknownSize( iter, Spliterator.ORDERED | Spliterator.NONNULL), false); }
Example #30
Source File: Utils.java From iroha-java with Apache License 2.0 | 5 votes |
private static Iterable<TransactionOuterClass.Transaction> createBatch( Iterable<TransactionOuterClass.Transaction> list, BatchType batchType, KeyPair keyPair) { final Iterable<String> batchHashes = getProtoBatchHashesHex(list); return StreamSupport.stream(list.spliterator(), false) .map(tx -> Transaction .parseFrom(tx) .makeMutable() .setBatchMeta(batchType, batchHashes) .sign(keyPair) .build() ) .collect(Collectors.toList()); }