Interview question
What is the Stream API in Java and how does it differ from Collections? Java में Stream API क्या है और Collections से कैसे अलग है?
Answer
| Aspect | Collection | Stream |
|---|---|---|
| Storage | Stores data in memory | No storage - computes elements on demand |
| Mutability | Can add/remove elements | Doesn't modify the source |
| Traversal | Can iterate multiple times | Consumed once, single-use |
| Evaluation | Eager - all operations happen immediately | Lazy - 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| पहलू | Collection | Stream |
|---|---|---|
| Storage | Memory में data store | कोई storage नहीं |
| Mutability | Add/remove हो सकता है | Source modify नहीं करता |
| Traversal | कई बार iterate | एक बार use, single-use |
| Evaluation | Eager | Lazy |
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?