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


Java Stream类代码示例

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


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

示例1: testMultiQuickSort

import io.vavr.collection.Stream; //导入依赖的package包/类
@Test
public void testMultiQuickSort() {

    DataTable table = DataTableBuilder
            .create("NewTable")
            .withColumn(Integer.class, "IndexCol", List.of(1, 2, 3, 4, 5, 6, 7))
            .withColumn(Integer.class, "NumberCol", List.of(2, 3, 3, 4, 4, 5, 5))
            .withColumn(String.class, "StringCol", List.of("aa", "bb", "cc", "dd", "ee", "ff", "gg"))
            .build().get();

    SortItem sortOne = new SortItem("NumberCol", SortOrder.Ascending);
    SortItem sortTwo = new SortItem("StringCol", SortOrder.Descending);

    Try<DataView> view = table.quickSort(Stream.of(sortOne, sortTwo));

    assertTrue(view.isSuccess());

    // Check Index Column values are as expected.
    assertTrue(view.get().row(0).getAs(Integer.class, "IndexCol") == 1);
    assertTrue(view.get().row(1).getAs(Integer.class, "IndexCol") == 3);
    assertTrue(view.get().row(2).getAs(Integer.class, "IndexCol") == 2);
    assertTrue(view.get().row(3).getAs(Integer.class, "IndexCol") == 5);
    assertTrue(view.get().row(4).getAs(Integer.class, "IndexCol") == 4);
    assertTrue(view.get().row(5).getAs(Integer.class, "IndexCol") == 7);
    assertTrue(view.get().row(6).getAs(Integer.class, "IndexCol") == 6);
}
 
开发者ID:martincooper,项目名称:java-datatable,代码行数:27,代码来源:QuickSortTests.java

示例2: testDataTableSortingPerformance

import io.vavr.collection.Stream; //导入依赖的package包/类
@Ignore
@Test
public void testDataTableSortingPerformance() {
    DataTable table = DataTableBuilder
            .create("NewTable")
            .withColumn(String.class, "StrCol", randomStringData(ROW_COUNT))
            .withColumn(Integer.class, "IntCol", randomIntegerData(ROW_COUNT))
            .withColumn(Double.class, "DoubleCol", randomDoubleData(ROW_COUNT))
            .withColumn(Boolean.class, "BoolCol", randomBooleanData(ROW_COUNT))
            .build().get();

    SortItem sortOne = new SortItem("StrCol");
    SortItem sortTwo = new SortItem("IntCol", SortOrder.Descending);
    SortItem sortThree = new SortItem("DoubleCol");
    SortItem sortFour = new SortItem("BoolCol", SortOrder.Descending);

    long startTime = System.nanoTime();

    Try<DataView> view = table.quickSort(Stream.of(sortOne, sortTwo, sortThree, sortFour));

    long endTime = System.nanoTime();
    long duration = (endTime - startTime) / 1000000;

    System.out.println("Sorting took " + duration + " milliseconds");
}
 
开发者ID:martincooper,项目名称:java-datatable,代码行数:26,代码来源:DataTableSortingTests.java

示例3: shouldDecorateSupplier

import io.vavr.collection.Stream; //导入依赖的package包/类
@Test
public void shouldDecorateSupplier() throws Throwable {
    // Given the HelloWorldService returns Hello world
    BDDMockito.given(helloWorldService.returnHelloWorld()).willReturn("Hello world");

    // And measure the call with a Timer
    Supplier<String> timedSupplier = Timer.decorateSupplier(timer, helloWorldService::returnHelloWorld);

    Stream.range(0,2).forEach((i) -> timedSupplier.get());

    assertThat(timer.getMetrics().getNumberOfTotalCalls()).isEqualTo(2);
    assertThat(timer.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(2);
    assertThat(timer.getMetrics().getNumberOfFailedCalls()).isEqualTo(0);
    // Then the helloWorldService should be invoked 1 time
    BDDMockito.then(helloWorldService).should(times(2)).returnHelloWorld();
}
 
开发者ID:resilience4j,项目名称:resilience4j,代码行数:17,代码来源:TimerTest.java

示例4: shouldExecuteSupplier

import io.vavr.collection.Stream; //导入依赖的package包/类
@Test
public void shouldExecuteSupplier() throws Throwable {
    // Given the HelloWorldService returns Hello world
    BDDMockito.given(helloWorldService.returnHelloWorld()).willReturn("Hello world").willThrow(new IllegalArgumentException("BAM!"));

    // And measure the call with a Timer
    Stream.range(0,2).forEach((i) -> {
        try{
            timer.executeSupplier(helloWorldService::returnHelloWorld);
        }catch (Exception e){
            Assertions.assertThat(e).isInstanceOf(IllegalArgumentException.class);
        }
    });

    assertThat(timer.getMetrics().getNumberOfTotalCalls()).isEqualTo(2);
    assertThat(timer.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1);
    assertThat(timer.getMetrics().getNumberOfFailedCalls()).isEqualTo(1);

    // Then the helloWorldService should be invoked 1 time
    BDDMockito.then(helloWorldService).should(times(2)).returnHelloWorld();
}
 
开发者ID:resilience4j,项目名称:resilience4j,代码行数:22,代码来源:TimerTest.java

示例5: traverse

import io.vavr.collection.Stream; //导入依赖的package包/类
/**
 * @return Type class for traversables with traverse / sequence operations
 */
public static <C2,T> Traverse<stream> traverse(){

    BiFunction<Applicative<C2>,StreamKind<Higher<C2, T>>,Higher<C2, StreamKind<T>>> sequenceFn = (ap, list) -> {

        Higher<C2,StreamKind<T>> identity = ap.unit(widen(Stream.empty()));

        BiFunction<Higher<C2,StreamKind<T>>,Higher<C2,T>,Higher<C2,StreamKind<T>>> combineToStream =   (acc, next) -> ap.apBiFn(ap.unit((a, b) -> widen(StreamKind.narrow(a).append(b))),
                acc,next);

        BinaryOperator<Higher<C2,StreamKind<T>>> combineStreams = (a, b)-> ap.apBiFn(ap.unit((l1, l2)-> widen(StreamKind.narrow(l1).appendAll(l2))),a,b); ;

        return ReactiveSeq.fromIterable(StreamKind.narrow(list))
                .reduce(identity,
                        combineToStream,
                        combineStreams);


    };
    BiFunction<Applicative<C2>,Higher<stream,Higher<C2, T>>,Higher<C2, Higher<stream,T>>> sequenceNarrow  =
            (a,b) -> StreamKind.widen2(sequenceFn.apply(a, narrowK(b)));
    return General.traverse(zippingApplicative(), sequenceNarrow);
}
 
开发者ID:aol,项目名称:cyclops,代码行数:26,代码来源:Streams.java

示例6: create

import io.vavr.collection.Stream; //导入依赖的package包/类
@Override
Seq<?> create(List<Object> result, DeserializationContext ctxt) throws JsonMappingException {
    if (Array.class.isAssignableFrom(javaType.getRawClass())) {
        return Array.ofAll(result);
    }
    if (Queue.class.isAssignableFrom(javaType.getRawClass())) {
        return Queue.ofAll(result);
    }
    if (Stream.class.isAssignableFrom(javaType.getRawClass())) {
        return Stream.ofAll(result);
    }
    if (Vector.class.isAssignableFrom(javaType.getRawClass())) {
        return Vector.ofAll(result);
    }
    // default deserialization [...] -> Seq
    return io.vavr.collection.List.ofAll(result);
}
 
开发者ID:vavr-io,项目名称:vavr-jackson,代码行数:18,代码来源:SeqDeserializer.java

示例7: add

import io.vavr.collection.Stream; //导入依赖的package包/类
/**
 * Returns a new DataTable with the additional row appended.
 *
 * @param rowValues The values to append to the row.
 * @return Returns a new DataTable with the row appended.
 */
public Try<DataTable> add(Object[] rowValues) {
    return Match(mapValuesToColumns(Stream.of(rowValues))).of(
            Case($Success($()), this::addRow),
            Case($Failure($()), Try::failure)
    );
}
 
开发者ID:martincooper,项目名称:java-datatable,代码行数:13,代码来源:DataRowCollectionModifiable.java

示例8: immutable

import io.vavr.collection.Stream; //导入依赖的package包/类
@Test
public void immutable() {
    Vector<Integer> vector = Stream.range(0, COUNT).foldLeft(Vector.empty(), Vector::append);
    assertEquals(COUNT, vector.length());
    ResultWrapper<Vector<Integer>> resultWrapper = new ResultWrapper<>(vector);
    keepProfilerAlive(resultWrapper);
}
 
开发者ID:netzwerg,项目名称:paleo,代码行数:8,代码来源:ProfilingTest.java

示例9: testStreamOfTuple

import io.vavr.collection.Stream; //导入依赖的package包/类
@Test
public void testStreamOfTuple() throws Exception {
    String src00 = "A";
    String src01 = "B";
    Tuple2<String, String> src0 = Tuple.of(src00, src01);
    Stream<Tuple2<String, String>> src = Stream.of(src0);
    String json = MAPPER.writeValueAsString(new ParameterizedStreamPojo<>(src));
    Assert.assertEquals(json, "{\"value\":[[\"A\",\"B\"]]}");
    ParameterizedStreamPojo<io.vavr.Tuple2<java.lang.String, java.lang.String>> restored = 
            MAPPER.readValue(json, new TypeReference<ParameterizedStreamPojo<io.vavr.Tuple2<java.lang.String, java.lang.String>>>(){});
    Assert.assertEquals(src, restored.getValue());
}
 
开发者ID:vavr-io,项目名称:vavr-jackson,代码行数:13,代码来源:ParameterizedPojoTest.java

示例10: of

import io.vavr.collection.Stream; //导入依赖的package包/类
static IntervalFunction of(long intervalMillis, Function<Long, Long> backoffFunction) {
    checkInterval(intervalMillis);
    requireNonNull(backoffFunction);

    return (attempt) -> {
        checkAttempt(attempt);
        return Stream.iterate(intervalMillis, backoffFunction).get(attempt - 1);
    };
}
 
开发者ID:resilience4j,项目名称:resilience4j,代码行数:10,代码来源:IntervalFunction.java

示例11: doTicksYahooFinanceHistoric

import io.vavr.collection.Stream; //导入依赖的package包/类
private CharSeq doTicksYahooFinanceHistoric(final Ticker ticker, final LocalDate date) {
  logger.info("doTicksYahooFinanceHistoric:{},{}", ticker.toString(), date);

  // is ticker new?
  List<Ticker> missing = kennel.findMissingTickers.apply(kennel.dogs, List.of(ticker));
  kennel.dogs = kennel.createAndAddNewDogs.apply(kennel.dogs, missing);

  // get the dogs for the requested tickers...
  DomainObjectGenerator myDog = kennel.findMyDog.apply(kennel.dogs, ticker).get();

  logger.debug("manager:{}", kennel.dogs.toJavaList());
  logger.debug("dogs:{}", myDog.toString());
  logger.debug("missing:{}", missing.toJavaList());

  // generate a historic series of TickJson...

  // OffsetDateTime startDate = OffsetDateTime.now().minusDays(daysAgo).withHour(0).withMinute(0).withSecond(0);
  OffsetDateTime startDate = OffsetDateTime.of(date, LocalTime.MIDNIGHT, ZoneOffset.UTC);
  List<TickJson> ticks = Stream.range(0, ChronoUnit.DAYS.between(startDate, OffsetDateTime.now()))
      .map(x -> myDog.newTick(startDate.plusDays(x)))
      .reverse()
      .toList();

  // format the results specific to this mock API...
  YahooFinanceHistoric yfh = YahooFinanceHistoric.of(ticks);

  // .map(tick -> YahooFinanceHistoric.of(tick))
  // .map(yfr -> yfr.toString())
  // .map(CharSeq::of)
  // .getOrElse(CharSeq.empty())
  // .reduce((x, xs) -> x.append('\n').appendAll(xs));

  CharSeq results = CharSeq.of(yfh.toString());
  logger.info("results:{}", results.toString());
  return results;
}
 
开发者ID:the-james-burton,项目名称:the-turbine,代码行数:37,代码来源:FinanceController.java

示例12: parseCompanies

import io.vavr.collection.Stream; //导入依赖的package包/类
private List<LseCompany> parseCompanies(String input) {
  Sheet sheet = extractSheet(input);

  // validate the sheet...
  Row headerRow = findAndValidateHeaderRow(sheet, headerRowNumber, expectedCompanyHeaders);

  // log out the cell types...
  logger.info(findHeaderCellTypes(sheet, headerRow)
      .map(t -> format("%s:%s", t._1, t._2))
      .reduce((a, b) -> format("%s, %s", a, b)));

  // parse the sheet into Company pojos...
  List<LseCompany> companies = Stream.ofAll((Iterable<Row>) sheet)
      .filter(row -> row.getRowNum() > 6)
      .map(row -> LseCompany.of(
          row.getCell(0).getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
          StringUtils.trim(row.getCell(1).getStringCellValue()),
          (int) row.getCell(2).getNumericCellValue(),
          StringUtils.trim(row.getCell(3).getStringCellValue()),
          StringUtils.trim(row.getCell(4).getStringCellValue()),
          StringUtils.trim(row.getCell(5).getStringCellValue()),
          StringUtils.trim(row.getCell(6).getStringCellValue()),
          row.getCell(7).getNumericCellValue(),
          convertToBoolean.apply(row.getCell(8).getStringCellValue())))
      .toList();

  return companies;
}
 
开发者ID:the-james-burton,项目名称:the-turbine,代码行数:29,代码来源:LseParser.java

示例13: findHeaderCellTypes

import io.vavr.collection.Stream; //导入依赖的package包/类
private List<Tuple2<String, CellType>> findHeaderCellTypes(Sheet sheet, Row headersAtRow) {
  Row firstRow = sheet.getRow(headerRowNumber + 1);
  return Stream.ofAll(IteratorUtils.asIterable(headersAtRow.cellIterator()))
      .zip(IteratorUtils.asIterable(firstRow.cellIterator()))
      .map(t -> Tuple.of(t._1.getStringCellValue(), t._2.getCellTypeEnum()))
      .toList();
  // .toJavaMap(v -> Tuple.of(v._1.getStringCellValue(), v._2.getCellTypeEnum()));
  // .forEach(t -> logger.info("{}:{}", t._1.getStringCellValue(), t._2.getCellTypeEnum().toString()));
}
 
开发者ID:the-james-burton,项目名称:the-turbine,代码行数:10,代码来源:LseParser.java

示例14: findAndValidateHeaderRow

import io.vavr.collection.Stream; //导入依赖的package包/类
private Row findAndValidateHeaderRow(Sheet sheet, Integer headersAtRow, List<String> expected) {
  Row headerRow = sheet.getRow(headersAtRow);
  List<String> actualHeaders = Stream.ofAll(IteratorUtils.asIterable(headerRow.cellIterator()))
      .map(cell -> cell.getStringCellValue())
      .toList();
  boolean isValid = actualHeaders.containsAll(expected);
  if (!isValid) {
    throw new RuntimeException("The expected header row is not present in the expected place. Maybe the sheet has changed?");
  }
  return headerRow;
}
 
开发者ID:the-james-burton,项目名称:the-turbine,代码行数:12,代码来源:LseParser.java

示例15: receiveSimulatedMessages

import io.vavr.collection.Stream; //导入依赖的package包/类
/**
 * TESTING ONLY
 */
@ManagedOperation
public void receiveSimulatedMessages(int n) {
  Stream.range(0, n)
      .forEach(x -> Try.run(() -> receiveSimulatedMessage())
          .orElseRun((e) -> logger.info("could not receive {} simulated messages:{}", n, e)));
}
 
开发者ID:the-james-burton,项目名称:the-turbine,代码行数:10,代码来源:AmqpTickReceiver.java


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