Java Code Examples for io.vavr.collection.Stream

The following examples show how to use io.vavr.collection.Stream. These examples are extracted from open source projects. 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 Project: tutorials   Source File: VavrSampler.java    License: 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 Project: tutorials   Source File: VavrSampler.java    License: 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 3
Source Project: java-datatable   Source File: QuickSortTests.java    License: 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 4
Source Project: java-datatable   Source File: DataTableSortingTests.java    License: 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 Project: resilience4j   Source File: TimerTest.java    License: 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 6
Source Project: tutorials   Source File: CollectionFactoryMethodsUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenAStream_whenCreated_thenCorrect() {
    Stream<Integer> stream = Stream(1, 2, 3, 4, 5);
    
    assertEquals(stream.size(), 5);
    assertEquals(stream.get(0).intValue(), 1);
}
 
Example 7
Source Project: tutorials   Source File: VavrSampler.java    License: 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 8
@Test
public void shouldOpenBackendACircuitBreaker() {
	// When
	Stream.rangeClosed(1,2).forEach((count) -> produceFailure(BACKEND_A));

	// Then
	checkHealthStatus(BACKEND_A, State.OPEN);
}
 
Example 9
@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 10
@Test
public void shouldOpenBackendBCircuitBreaker() {
	// When
	Stream.rangeClosed(1,4).forEach((count) -> produceFailure(BACKEND_B));

	// Then
	checkHealthStatus(BACKEND_B, State.OPEN);
}
 
Example 11
@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 12
@Test
public void shouldOpenBackendACircuitBreaker() {
	// When
	Stream.rangeClosed(1,2).forEach((count) -> produceFailure(BACKEND_A));

	// Then
	checkHealthStatus(BACKEND_A, State.OPEN);
}
 
Example 13
@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 14
@Test
public void shouldOpenBackendBCircuitBreaker() {
	// When
	Stream.rangeClosed(1,4).forEach((count) -> produceFailure(BACKEND_B));

	// Then
	checkHealthStatus(BACKEND_B, State.OPEN);
}
 
Example 15
@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 16
@Test
public void shouldOpenBackendBCircuitBreaker() {
	// When
	Stream.rangeClosed(1,4).forEach((count) -> produceFailure(BACKEND_B));

	// Then
	checkHealthStatus(BACKEND_B, State.OPEN);
}
 
Example 17
@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 18
@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 19
Source Project: articles   Source File: VavrHammingDecoder.java    License: 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 20
Source Project: tutorials   Source File: VavrSampler.java    License: 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 21
Source Project: tutorials   Source File: StreamIndices.java    License: MIT License 5 votes vote down vote up
public static List<String> getOddIndexedStringsVersionTwo(String[] names) {
    List<String> oddIndexedNames = Stream.of(names)
        .zipWithIndex()
        .filter(tuple -> tuple._2 % 2 == 1)
        .map(tuple -> tuple._1)
        .toJavaList();
    return oddIndexedNames;
}
 
Example 22
Source Project: articles   Source File: HammingHelper.java    License: Apache License 2.0 5 votes vote down vote up
Stream<Integer> parityIndicesSequence(int startIndex, int endExclusive) {
    return Stream.from(startIndex, 1)
      .take(endExclusive - startIndex)
      .zipWithIndex()
      .filter(t -> (t._2 % ((2 * (startIndex + 1)))) < startIndex + 1)
      .map(t -> t._1)
      .drop(1);
}
 
Example 23
Source Project: articles   Source File: VavrHammingEncoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("should always encode zeros to zeros")
void shouldEncodeZeros() {
    Stream.iterate("0", i -> i + "0")
      .take(1000)
      .map(it -> sut.encode(BinaryString.of(it)).getValue())
      .forEach(msg -> assertThat(msg).doesNotContain("1"));
}
 
Example 24
Source Project: tutorials   Source File: VavrSampler.java    License: MIT License 5 votes vote down vote up
public static void vavrFlatMapping() {
    System.out.println("Vavr flatMapping");
    System.out.println("====================================");
    Stream.of(42)
            .flatMap(i -> Stream.continually(() -> {
                System.out.println("nested call");
                return 42;
            }))
            .get(0);
}
 
Example 25
Source Project: reposilite   Source File: IndexApiController.java    License: 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 26
Source Project: reposilite   Source File: MetadataUtils.java    License: 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 27
Source Project: reposilite   Source File: MetadataUtils.java    License: 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 28
Source Project: reposilite   Source File: MetadataUtils.java    License: 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 29
Source Project: vavr-jackson   Source File: ParameterizedPojoTest.java    License: 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 30
/**
 * 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)
    );
}