Java : BaseStream con ejemplos

BaseStream (Java SE 21 & JDK 21) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de BaseStream<T,S extends BaseStream<T,S>>.

Nota :


Summary

Interfaz base para flujos, que son secuencias de elementos que soportan operaciones agregadas secuenciales y paralelas. (Traducción automática)

Class diagram

final BaseStream<String, Stream<String>> stream = Stream.of("aaa", "bbb", "ccc");
System.out.println("isParallel : " + stream.isParallel());

System.out.println("-- forEachRemaining --");
stream.iterator().forEachRemaining(value -> {
    System.out.println(value);
});

// Result
// ↓
//isParallel : false
//-- forEachRemaining --
//aaa
//bbb
//ccc

Methods

void close ()

Cierra esta secuencia, lo que provoca que se llame a todos los controladores de cierre de esta canalización de secuencia. (Traducción automática)

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

Files.writeString(path, """
        aaa
        bbb
        """);

try (final BaseStream<String, Stream<String>> stream = Files.lines(path)) {

    System.out.println("-- forEachRemaining --");
    stream.iterator().forEachRemaining(value -> {
        System.out.println(value);
    });
}

// Result
// ↓
//-- forEachRemaining --
//aaa
//bbb

An example without a try-with-resources statement.

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

final BaseStream<String, Stream<String>> stream = Files.lines(path);
try {
    System.out.println("-- forEachRemaining --");
    stream.iterator().forEachRemaining(value -> {
        System.out.println(value);
    });
} finally {
    stream.close();
}

// Result
// ↓
//-- forEachRemaining --
//aaa
//bbb

boolean isParallel ()

Devuelve si esta secuencia, si se ejecutara una operación de terminal, se ejecutaría en paralelo. (Traducción automática)

final var stream = Stream.of("aaa", "bbb", "ccc");
System.out.println(stream.isParallel()); // false

final var list = stream.peek(s -> {
    final var id = Thread.currentThread().threadId();
    System.out.println(s + " : " + "thread id = " + id);
}).toList();

System.out.println("list : " + list);

// Result
// ↓
//aaa : thread id = 1
//bbb : thread id = 1
//ccc : thread id = 1
//list : [aaa, bbb, ccc]
final var stream = Stream.of("aaa", "bbb", "ccc").parallel();
System.out.println(stream.isParallel()); // true

final var list = stream.peek(s -> {
    final var id = Thread.currentThread().threadId();
    System.out.println(s + " : " + "thread id = " + id);
}).toList();

System.out.println("list : " + list);

// Result
// ↓
//ccc : thread id = 1
//bbb : thread id = 1
//aaa : thread id = 32
//list : [aaa, bbb, ccc]

Iterator<T> iterator ()

Devuelve un iterador para los elementos de esta secuencia. (Traducción automática)

final BaseStream<String, Stream<String>> stream = Stream.of("aaa", "bbb", "ccc");

System.out.println("-- forEachRemaining --");
stream.iterator().forEachRemaining(value -> {
    System.out.println(value);
});

// Result
// ↓
//-- forEachRemaining --
//aaa
//bbb
//ccc

S onClose (Runnable closeHandler)

Devuelve una secuencia equivalente con un controlador cercano adicional. (Traducción automática)

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

Files.writeString(path, """
        aaa
        bbb
        """);

try (final var lines = Files.lines(path).onClose(() -> {
    System.out.println("onClose is called!");
})) {
    System.out.println("-- forEach --");
    lines.forEach(System.out::println);
}

// Result
// ↓
//-- forEach --
//aaa
//bbb
//onClose is called!
final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

try (final var lines = Files.lines(path)
        .onClose(() -> System.out.println("onClose 1"))
        .onClose(() -> System.out.println("onClose 2"))
        .onClose(() -> System.out.println("onClose 3"))
) {
    System.out.println("-- forEach --");
    lines.forEach(System.out::println);
}

// Result
// ↓
//-- forEach --
//aaa
//bbb
//onClose 1
//onClose 2
//onClose 3

S parallel ()

Devuelve una secuencia equivalente que es paralela. (Traducción automática)

final var stream = Stream.of("aaa", "bbb", "ccc");
System.out.println(stream.isParallel()); // false

final var parallelStream = stream.parallel();
System.out.println(parallelStream.isParallel()); // true

final var list = parallelStream.peek(s -> {
    final var id = Thread.currentThread().threadId();
    System.out.println(s + " : " + "thread id = " + id);
}).toList();

System.out.println("list : " + list);

// Result
// ↓
//aaa : thread id = 32
//ccc : thread id = 1
//bbb : thread id = 33
//list : [aaa, bbb, ccc]

S sequential ()

Devuelve una secuencia equivalente que es secuencial. (Traducción automática)

final var parallelStream = Stream.of("aaa", "bbb", "ccc").parallel();
System.out.println(parallelStream.isParallel()); // true

final var sequentialStream = parallelStream.sequential();
System.out.println(sequentialStream.isParallel()); // false

final var list = sequentialStream.peek(s -> {
    final var id = Thread.currentThread().threadId();
    System.out.println(s + " : " + "thread id = " + id);
}).toList();

System.out.println("list : " + list);

// Result
// ↓
//aaa : thread id = 1
//bbb : thread id = 1
//ccc : thread id = 1
//list : [aaa, bbb, ccc]

Spliterator<T> spliterator ()

Devuelve un divisor para los elementos de esta secuencia. (Traducción automática)

final BaseStream<String, Stream<String>> stream = Stream.of("aaa", "bbb", "ccc");
final var spliterator = stream.spliterator();

System.out.println("-- forEachRemaining --");
spliterator.forEachRemaining(value -> {
    System.out.println(value);
});

// Result
// ↓
//-- forEachRemaining --
//aaa
//bbb
//ccc

S unordered ()

Devuelve una secuencia equivalente que no está ordenada. (Traducción automática)

The unordered method may make stateful operations (such as distinct and sorted) more efficient.

final var list = new ArrayList<String>();
for (int i = 0; i < 200000; i++) {
    list.add(Integer.toHexString(i / 2));
}

// An example with unordered.
{
    final var start = System.nanoTime();

    for (int i = 0; i < 100; i++) {
        final var stream = list.parallelStream().unordered();
        final var result = stream.map(String::toUpperCase).distinct().toList();
    }

    final var time = System.nanoTime() - start;

    System.out.println((time / 1000000000.0) + " sec."); // 2.6085375 sec.
}

// An example without unordered.
{
    final var start = System.nanoTime();

    for (int i = 0; i < 100; i++) {
        final var stream = list.parallelStream();
        final var result = stream.map(String::toUpperCase).distinct().toList();
    }

    final var time = System.nanoTime() - start;

    System.out.println((time / 1000000000.0) + " sec."); // 3.4048646 sec.
}

Related posts

To top of page