Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the Stream API in Java and how does it differ from Collections? Java में Stream API क्या है और Collections से कैसे अलग है?

Answer
AspectCollectionStream
StorageStores data in memoryNo storage - computes elements on demand
MutabilityCan add/remove elementsDoesn't modify the source
TraversalCan iterate multiple timesConsumed once, single-use
EvaluationEager - all operations happen immediatelyLazy - intermediate ops run only when a terminal op is invoked
import java.util.stream.*;

List<String> names = List.of('Charlie', 'Alice', 'Bob', 'Anna');

// A stream pipeline: source -> intermediate operations -> terminal operation
List<String> result = names.stream()                 // create stream from collection
    .filter(name -> name.startsWith('A'))              // intermediate: lazy, returns a stream
    .map(String::toUpperCase)                            // intermediate: lazy, returns a stream
    .sorted()                                             // intermediate: lazy
    .collect(Collectors.toList());                       // terminal: triggers execution

System.out.println(result);  // [ALICE, ANNA]

// Streams are single-use - reusing a consumed stream throws an exception
Stream<String> stream = names.stream();
stream.forEach(System.out::println);
// stream.forEach(System.out::println);  // IllegalStateException: stream has already been operated upon

// Lazy evaluation demonstration
Stream<String> lazyStream = names.stream()
    .filter(name -> {
        System.out.println('Filtering: ' + name);
        return name.length() > 3;
    });
// Nothing printed yet - filter() hasn't actually run because there's
// no terminal operation yet
long count = lazyStream.count();  // NOW the filter actually executes
पहलूCollectionStream
StorageMemory में data storeकोई storage नहीं
MutabilityAdd/remove हो सकता हैSource modify नहीं करता
Traversalकई बार iterateएक बार use, single-use
EvaluationEagerLazy
import java.util.stream.*;

List<String> names = List.of('Charlie', 'Alice', 'Bob', 'Anna');

List<String> result = names.stream()
    .filter(name -> name.startsWith('A'))
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());

System.out.println(result);  // [ALICE, ANNA]

// Streams single-use हैं
Stream<String> stream = names.stream();
stream.forEach(System.out::println);
// stream.forEach(System.out::println);  // IllegalStateException

// Lazy evaluation
Stream<String> lazyStream = names.stream()
    .filter(name -> {
        System.out.println('Filtering: ' + name);
        return name.length() > 3;
    });
// अभी कुछ print नहीं हुआ - terminal operation नहीं है
long count = lazyStream.count();  // अब filter चलता है

Was this answer clear?