01-java-foundations

Java Collections and Java 8+: Streams, Optionals, Functional Interfaces

Learn Java collections, modern Java 8 features like streams, optionals, lambdas, and functional interfaces for backend code.

backend-engineerjavacollectionsstreamsfunctional

Java Collections and Java 8+

Backend Java code relies on collections, streams, and modern language APIs for clean and reliable business logic.

Collection Types

  • List: ordered collection with duplicates.
  • Set: unique elements.
  • Map: key-value pairs.
  • Queue: FIFO or priority processing.
  • Deque: double-ended queue.

Common Implementations

  • ArrayList: fast random access, resizable array.
  • LinkedList: fast insert/remove at ends, poor random access.
  • HashMap: average O(1) lookup, unsorted.
  • LinkedHashMap: maintains insertion order.
  • TreeMap: sorted keys, O(log n) operations.
  • HashSet: backed by HashMap, unique elements.
  • TreeSet: sorted set.

HashCode and Equals

  • Implement equals() and hashCode() consistently for objects used in hashed collections.
  • Violating the contract breaks HashMap, HashSet, and caching semantics.

Comparable and Comparator

  • Comparable defines natural ordering with compareTo().
  • Comparator defines external ordering strategies.
  • Use comparators for sorting by different fields without changing object classes.

Streams and Functional Programming

Lambda Expressions

  • Use lambdas for concise behavior passed into stream operations and callbacks.

Functional Interfaces

  • A functional interface has a single abstract method.
  • Common examples: Function, Predicate, Consumer, Supplier.
  • Predicate<T> evaluates a boolean condition.
  • Consumer<T> consumes a value without returning one.
  • Supplier<T> produces a value without input.

Streams

  • Use Stream for declarative collection processing.
  • Prefer streams for transformations and filters, but avoid them for simple loops when performance matters.

Optional

  • Optional<T> represents a value that may or may not be present.
  • Use it for return values, not for fields or parameters.

Method References

  • Use Class::method or instance::method to make lambda expressions shorter and clearer.