io.vavr.collection.Stream Java Examples

The following examples show how to use io.vavr.collection.Stream. 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: VavrSampler.java    From tutorials with MIT License 6 votes vote down vote up
public static void vavrStreamManipulation() {
    System.out.println("Vavr Stream Manipulation");
    System.out.println("====================================");
    List<String> stringList = new ArrayList<>();
    stringList.add("foo");
    stringList.add("bar");
    stringList.add("baz");
    Stream<String> vavredStream = Stream.ofAll(stringList);
    vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
    Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
    vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
    stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
    Stream<String> deletionStream = vavredStream.remove("bar");
    deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));

}
 
Example #2
Source File: QuickSortTests.java    From java-datatable with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: TimerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldExecuteSupplier() throws Throwable {
    given(helloWorldService.returnHelloWorld()).willReturn("Hello world")
        .willThrow(new IllegalArgumentException("BAM!"));

    Stream.range(0, 2).forEach((i) -> {
        try {
            timer.executeSupplier(helloWorldService::returnHelloWorld);
        } catch (Exception e) {
            assertThat(e).isInstanceOf(IllegalArgumentException.class);
        }
    });

    assertThat(timer.getMetrics().getNumberOfTotalCalls()).isEqualTo(2);
    assertThat(timer.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1);
    assertThat(timer.getMetrics().getNumberOfFailedCalls()).isEqualTo(1);
    then(helloWorldService).should(times(2)).returnHelloWorld();
}
 
Example #4
Source File: DataTableSortingTests.java    From java-datatable with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #5
Source File: VavrSampler.java    From tutorials with MIT License 6 votes vote down vote up
public static void vavrStreamManipulation() {
    System.out.println("Vavr Stream Manipulation");
    System.out.println("====================================");
    List<String> stringList = new ArrayList<>();
    stringList.add("foo");
    stringList.add("bar");
    stringList.add("baz");
    Stream<String> vavredStream = Stream.ofAll(stringList);
    vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
    Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
    vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
    stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
    Stream<String> deletionStream = vavredStream.remove("bar");
    deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));

}
 
Example #6
Source File: IndexApiController.java    From reposilite with Apache License 2.0 5 votes vote down vote up
@Override
public Context handleContext(Context ctx) {
    Reposilite.getLogger().info(ctx.req.getRequestURI() + " API");
    String uri = RepositoryUtils.normalizeUri(configuration, StringUtils.replaceFirst(ctx.req.getRequestURI(), "/api", StringUtils.EMPTY));

    if ((configuration.isFullAuthEnabled() || !configuration.isIndexingEnabled()) && authenticator.authUri(ctx.headerMap(), uri).containsError()) {
        return ErrorUtils.error(ctx, HttpStatus.SC_UNAUTHORIZED, "Unauthorized request");
    }

    File requestedFile = repositoryService.getFile(uri);

    if (requestedFile.getName().equals("latest")) {
        File parent = requestedFile.getParentFile();

        if (parent != null && parent.exists()) {
            File[] files = MetadataUtils.toSortedVersions(parent);
            File latest = ArrayUtils.getFirst(files);

            if (latest != null) {
                return ctx.json(FileDto.of(latest));
            }
        }
    }

    if (!requestedFile.exists()) {
        return ErrorUtils.error(ctx, HttpStatus.SC_NOT_FOUND, "File not found");
    }

    if (requestedFile.isFile()) {
        return ctx.json(FileDto.of(requestedFile));
    }

    return ctx.json(new FileListDto(Stream.of(FilesUtils.listFiles(requestedFile))
            .map(FileDto::of)
            .transform(stream -> MetadataUtils.toSorted(stream, FileDto::getName, FileDto::isDirectory))
            .toJavaList()));
}
 
Example #7
Source File: ParameterizedPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testStreamOfString() throws Exception {
    String src0 = "A";
    String src1 = "B";
    String src2 = "C";
    Stream<String> src = Stream.of(src0, src1, src2);
    String json = MAPPER.writeValueAsString(new ParameterizedStreamPojo<>(src));
    Assertions.assertEquals(json, "{\"value\":[\"A\",\"B\",\"C\"]}");
    ParameterizedStreamPojo<java.lang.String> restored =
            MAPPER.readValue(json, new TypeReference<ParameterizedStreamPojo<java.lang.String>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #8
Source File: MetadataUtils.java    From reposilite with Apache License 2.0 5 votes vote down vote up
protected static File[] toBuildFiles(File artifactDirectory, String identifier) {
    return Stream.of(FilesUtils.listFiles(artifactDirectory))
            .filter(file -> file.getName().contains(identifier + ".") || file.getName().contains(identifier + "-"))
            .filterNot(file -> file.getName().endsWith(".md5"))
            .filterNot(file -> file.getName().endsWith(".sha1"))
            .transform(stream -> toSorted(stream, File::getName, File::isDirectory))
            .toJavaArray(File[]::new);
}
 
Example #9
Source File: MetadataUtils.java    From reposilite with Apache License 2.0 5 votes vote down vote up
protected static String[] toSortedIdentifiers(String artifact, String version, File[] builds) {
    return Stream.of(builds)
            .map(build -> toIdentifier(artifact, version, build))
            .filterNot(StringUtils::isEmpty)
            .distinct()
            .transform(stream -> toSorted(stream, Function.identity(), identifier -> true))
            .toJavaArray(String[]::new);
}
 
Example #10
Source File: MetadataUtils.java    From reposilite with Apache License 2.0 5 votes vote down vote up
public static File[] toSortedBuilds(File artifactDirectory) {
    return Stream.of(FilesUtils.listFiles(artifactDirectory))
            .filter(File::isFile)
            .filter(file -> file.getName().endsWith(".pom"))
            .transform(stream -> toSorted(stream, File::getName, File::isDirectory))
            .toJavaArray(File[]::new);
}
 
Example #11
Source File: VavrSampler.java    From tutorials with MIT License 5 votes vote down vote up
public static void jdkFlatMapping() {
    System.out.println("Java flatMapping");
    System.out.println("====================================");
    java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
        System.out.println("nested call");
        return 42;
    })).findAny();
}
 
Example #12
Source File: ReactiveCircuitBreakerTest.java    From resilience4j-spring-boot2-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCloseBackendACircuitBreaker() {
	transitionToOpenState(BACKEND_A);
	circuitBreakerRegistry.circuitBreaker(BACKEND_A).transitionToHalfOpenState();

	// When
	Stream.rangeClosed(1,3).forEach((count) -> produceSuccess(BACKEND_A));

	// Then
	checkHealthStatus(BACKEND_A, State.CLOSED);
}
 
Example #13
Source File: CircuitBreakerTest.java    From resilience4j-spring-boot2-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldOpenBackendBCircuitBreaker() {
	// When
	Stream.rangeClosed(1,4).forEach((count) -> produceFailure(BACKEND_B));

	// Then
	checkHealthStatus(BACKEND_B, State.OPEN);
}
 
Example #14
Source File: CircuitBreakerTest.java    From resilience4j-spring-boot2-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCloseBackendBCircuitBreaker() {
	transitionToOpenState(BACKEND_B);
	circuitBreakerRegistry.circuitBreaker(BACKEND_B).transitionToHalfOpenState();

	// When
	Stream.rangeClosed(1,3).forEach((count) -> produceSuccess(BACKEND_B));

	// Then
	checkHealthStatus(BACKEND_B, State.CLOSED);
}
 
Example #15
Source File: ReactiveCircuitBreakerTest.java    From resilience4j-spring-boot2-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldOpenBackendBCircuitBreaker() {
	// When
	Stream.rangeClosed(1,4).forEach((count) -> produceFailure(BACKEND_B));

	// Then
	checkHealthStatus(BACKEND_B, State.OPEN);
}
 
Example #16
Source File: CircuitBreakerTest.java    From resilience4j-spring-boot2-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCloseBackendACircuitBreaker() {
	transitionToOpenState(BACKEND_A);
	circuitBreakerRegistry.circuitBreaker(BACKEND_A).transitionToHalfOpenState();

	// When
	Stream.rangeClosed(1,3).forEach((count) -> produceSuccess(BACKEND_A));

	// Then
	checkHealthStatus(BACKEND_A, State.CLOSED);
}
 
Example #17
Source File: VavrHammingDecoder.java    From articles with Apache License 2.0 5 votes vote down vote up
private List<Integer> indexesOfInvalidParityBits(EncodedString input) {
    return Stream.iterate(1, i -> i * 2)
      .takeWhile(it -> it < input.getValue().length())
      .filter(it -> helper.parityIndicesSequence(it - 1, input.getValue().length())
        .map(v -> toBinaryInt(input, v))
        .fold(toBinaryInt(input, it - 1), (a, b) -> a ^ b) != 0)
      .toList();
}
 
Example #18
Source File: VavrSampler.java    From tutorials with MIT License 5 votes vote down vote up
public static void vavrStreamElementAccess() {
    System.out.println("Vavr Element Access");
    System.out.println("====================================");
    Stream<Integer> vavredStream = Stream.ofAll(intArray);
    System.out.println("Vavr index access: " + vavredStream.get(2));
    System.out.println("Vavr head element access: " + vavredStream.get());

    Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
    System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
 
Example #19
Source File: DataRowCollectionModifiable.java    From java-datatable with Apache License 2.0 5 votes vote down vote up
/**
 * 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)
    );
}
 
Example #20
Source File: VavrSampler.java    From tutorials with MIT License 5 votes vote down vote up
public static void vavrParallelStreamAccess() {

        System.out.println("Vavr Stream Concurrent Modification");
        System.out.println("====================================");
        Stream<Integer> vavrStream = Stream.ofAll(intList);
        // intList.add(5);
        vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));

        // Stream<Integer> wrapped = Stream.ofAll(intArray);
        // intArray[2] = 5;
        // wrapped.forEach(i -> System.out.println("Vavr looped " + i));
    }
 
Example #21
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
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 StreamOfTuple().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[[\"A\",\"B\"]]}");
    StreamOfTuple restored = MAPPER.readValue(json, StreamOfTuple.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #22
Source File: PolymorphicPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testStream() throws Exception {
    Stream<I> src = Stream.of(new A(), new B());
    String json = MAPPER.writeValueAsString(new StreamPojo().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[{\"type\":\"a\"},{\"type\":\"b\"}]}");
    StreamPojo pojo = MAPPER.readValue(json, StreamPojo.class);
    Stream<I> restored = pojo.getValue();
    Assertions.assertTrue(restored.get(0) instanceof A);
    Assertions.assertTrue(restored.get(1) instanceof B);
}
 
Example #23
Source File: ProfilingTest.java    From paleo with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #24
Source File: IntervalFunction.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
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);
    };
}
 
Example #25
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testStreamOfString() throws Exception {
    String src0 = "A";
    String src1 = "B";
    String src2 = "C";
    Stream<String> src = Stream.of(src0, src1, src2);
    String json = MAPPER.writeValueAsString(new StreamOfString().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[\"A\",\"B\",\"C\"]}");
    StreamOfString restored = MAPPER.readValue(json, StreamOfString.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #26
Source File: TimerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecorateSupplier() throws Throwable {
    given(helloWorldService.returnHelloWorld()).willReturn("Hello world");
    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(helloWorldService).should(times(2)).returnHelloWorld();
}
 
Example #27
Source File: ParameterizedPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
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));
    Assertions.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>>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #28
Source File: TypeParser.java    From panda with Apache License 2.0 5 votes vote down vote up
@Autowired(order = 3, cycle = GenerationCycles.TYPES_LABEL, delegation = Delegation.CURRENT_AFTER)
void verifyProperties(Context context, @Ctx Type type, @Ctx TypeScope scope) {
    if (type.getState() != State.ABSTRACT) {
        type.getBases().stream()
                .flatMap(base -> base.getMethods().getProperties().stream())
                .filter(TypeMethod::isAbstract)
                .filter(method -> !type.getMethods().getMethod(method.getSimpleName(), method.getParameterTypes()).isDefined())
                .forEach(method -> {
                    throw new PandaParserFailure(context, "Missing implementation of &1" + method + "&r in &1" + type + "&r");
                });
    }

    if (type.getConstructors().getDeclaredProperties().isEmpty()) {
        type.getSuperclass().peek(superclass -> Stream.ofAll(superclass.getConstructors().getDeclaredProperties())
                .find(constructor -> constructor.getParameters().length > 0)
                .peek(constructorWithParameters -> {
                    throw new PandaParserFailure(context, "Type " + type + " does not implement any constructor from the base type " + constructorWithParameters.getType());
                })
        );

        type.getConstructors().declare(PandaConstructor.builder()
                .type(type)
                .callback((typeConstructor, frame, instance, arguments) -> scope.createInstance(frame, instance, typeConstructor, new Class<?>[0], arguments))
                .location(type.getLocation())
                .build());
    }
}
 
Example #29
Source File: PropertyBasedLongRunningUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
private Stream<String> stringsSupplier() {
    return Stream.from(0).map(i -> Match(i).of(
      Case($(divisibleByFive.and(divisibleByTwo)), "DividedByTwoAndFiveWithoutRemainder"),
      Case($(divisibleByFive), "DividedByFiveWithoutRemainder"),
      Case($(divisibleByTwo), "DividedByTwoWithoutRemainder"),
      Case($(), "")));
}
 
Example #30
Source File: DataGet.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Setup(Level.Iteration)
public void before(){
    vector = Vector.range(0,10000).map(i->""+i);;
    list = Stream.range(0,10000).map(i->""+i).toJavaList();
    js = io.vavr.collection.Vector.range(0,10000).map(i->""+i);
    guava = ImmutableList.copyOf(list);

}