Design Patterns and Collections in Java
24 Questions
2 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the purpose of the collect method in Java Streams?

  • To filter elements based on a condition.
  • To sort the elements in a Stream.
  • To perform a reduction operation on the elements of a Stream.
  • To accumulate elements into a container like List, Set, or custom structures. (correct)
  • What is the main difference between sequential streams and parallel streams in Java?

  • Sequential streams process elements in order using a single thread while parallel streams split the work into multiple threads. (correct)
  • Sequential streams are more efficient than parallel streams because they don't need to manage threads.
  • Sequential streams use multiple threads while parallel streams use a single thread.
  • Sequential streams process elements in order while parallel streams process elements in a random order.
  • How does the Optional class help avoid NullPointerExceptions?

  • It wraps a value and provides methods to handle both present and absent values. (correct)
  • It throws an exception if a null value is encountered.
  • It provides a default value to use if a null value is found.
  • It automatically checks for null values before executing operations.
  • Which of these is NOT a valid functional interface in Java?

    <p>Executor (A)</p> Signup and view all the answers

    What is the purpose of the default keyword in Java interfaces?

    <p>To provide default implementations for methods that can be overridden by concrete classes. (A)</p> Signup and view all the answers

    Which of these is a benefit of using Streams to refactor legacy code?

    <p>Streams offer a functional and declarative way to process data. (A)</p> Signup and view all the answers

    What is the main advantage of using a ReentrantLock compared to the synchronized keyword?

    <p>It provides more control over thread access (e.g., try-lock, fairness). (C)</p> Signup and view all the answers

    What is the primary use of a CompletableFuture?

    <p>To execute tasks concurrently and efficiently. (C)</p> Signup and view all the answers

    In the context of Spring Boot, which annotation is specifically used for components responsible for data persistence?

    <p>@Repository (D)</p> Signup and view all the answers

    What is the typical order of events in the Spring Bean lifecycle?

    <p>Instantiation -&gt; Dependency Injection -&gt; Initialization -&gt; Destruction (B)</p> Signup and view all the answers

    What is the main purpose of the @Transactional annotation in Spring?

    <p>Ensures the atomicity and consistency of database operations (B)</p> Signup and view all the answers

    In REST API design, which annotation is commonly used for handling exceptions?

    <p>@ExceptionHandler (A)</p> Signup and view all the answers

    What are the typical goals of a REST API gateway in a microservices architecture?

    <p>Provide a centralized access point for microservices, handle routing, and implement cross-cutting concerns like authentication and authorization (B)</p> Signup and view all the answers

    Which of the following is NOT a common tool for service discovery in a microservices architecture?

    <p>Spring Data (D)</p> Signup and view all the answers

    Imagine a microservices application where services need to communicate asynchronously. Besides REST, which of the following approaches would best support asynchronous communication?

    <p>Message Queues (e.g., Kafka) (C)</p> Signup and view all the answers

    In the context of design patterns, what is the main difference between a Singleton and a Prototype?

    <p>Singleton ensures a single instance per JVM, while Prototype creates a new instance each time it's requested (C)</p> Signup and view all the answers

    Which of the following best describes the key difference between HashMap and ConcurrentHashMap in Java's Collections Framework?

    <p>ConcurrentHashMap provides thread safety, while HashMap does not. (D)</p> Signup and view all the answers

    When would you choose to use a TreeSet over a HashSet in Java's Collections Framework?

    <p>When you need to maintain a sorted order for the elements in the collection. (A)</p> Signup and view all the answers

    Which of the following best characterizes the key difference between ArrayList and LinkedList in Java's Collections Framework?

    <p>LinkedList is better suited for frequent insertions and deletions, while ArrayList is better for random access. (D)</p> Signup and view all the answers

    How does HashSet in Java's Collections Framework handle duplicate elements?

    <p>HashSet uses hashCode and equals methods to determine uniqueness and discard duplicates. (A)</p> Signup and view all the answers

    What is the primary difference between the map and flatMap methods in Java's Stream API?

    <p>map applies a function to each element, while flatMap flattens a stream of streams. (C)</p> Signup and view all the answers

    Which of the following scenarios would benefit the most from using the Observer pattern?

    <p>Monitoring changes in the state of an object and notifying dependent objects. (C)</p> Signup and view all the answers

    What is the primary difference between the Factory Method and Abstract Factory design patterns?

    <p>Abstract Factory is used to create families of related objects, while Factory Method creates a single type of object. (D)</p> Signup and view all the answers

    Which design pattern is best suited for implementing a caching mechanism that allows for dynamic behavior based on the type of data being cached?

    <p>Decorator (D)</p> Signup and view all the answers

    Study Notes

    Inter-service Communication in Distributed Systems

    • Implement inter-service communication in a distributed system using tools or protocols.

    Design Patterns

    • Singleton vs. Prototype:

      • Singleton: one instance per JVM
      • Prototype: a new instance for each request
    • Factory Method vs. Abstract Factory:

      • Factory Method: creates objects of one type
      • Abstract Factory: creates families of related objects
    • Observer Pattern Benefits: Promotes loose coupling between subjects and observers.

    • Caching Mechanism (Decorator Pattern):

      • Wrap the original service with a caching layer to store results
    • Real-World Problem (Command Pattern):

      • Encapsulate booking logic into commands and execute them using an invoker for better flexibility

    Collections Framework

    • HashMap vs. ConcurrentHashMap:
      • HashMap: not thread-safe
      • ConcurrentHashMap: thread-safe

    TreeSet vs. HashSet

    • TreeSet: maintains elements in sorted order
    • HashSet: does not maintain order but provides O(1) time complexity for add,remove, and contains

    ArrayList vs. LinkedList

    • ArrayList: dynamic array, better for random access
    • LinkedList: doubly linked list, better for frequent insertions and deletions

    Duplicate Handling in HashSet

    • HashSet uses HashMap internally to ensure uniqueness based on hashCode and equals methods

    Designing a Data Structure for Unique Items

    • Use HashSet for constant-time operations.
    • Use ConcurrentHashMap for thread-safe operation. If needed, use Collections.synchronizedSet

    Fail-Fast vs. Fail-Safe Iterators

    • Fail-fast iterators (e.g., in ArrayList) throw ConcurrentModificationException if the collection is modified structurally during iteration.
    • Fail-safe iterators (e.g., in CopyOnWriteArrayList) operate on a snapshot of the collection.

    Stream API

    • map vs. flatMap:

      • map: transforms each element into another object, maintaining a one-to-one mapping
      • flatMap: flattens streams of streams into a single stream
    • collect Method:

      • accumulates elements of a Stream into a container (e.g., List, Set) or custom structures.
    • Sequential vs. Parallel Streams:

      • Sequential: processes elements in order, using a single thread
      • Parallel: splits the work into multiple threads, but adds overhead for thread management

    Group Employees by Department 

    • Use streams to group employees by department and calculate average salary for each department.

    Find Second Highest Number

    • Use streams to find the second highest number in a list of numbers.

    Java 8 Features

    • Optional: helps avoid NullPointerException by explicitly representing the presence or absence of a value

    • Functional Interfaces: (Function, Consumer, Supplier)

      • Function: Accepts an input and produces a result.
      • Consumer: Accepts an input but produces no result.
      • Supplier: Produces a result with no input.
    • default Keyword: Introduced to add methods to interfaces without breaking existing implementations.

    • Refactoring Legacy Code:

      • Replace loops with streams
      • Use lambda expressions for anonymous classes implementing functional interfaces
    • Method References Example:

      • Use method references (e.g., System.out::println) for cleaner code.

    Concurrency

    • synchronized vs. ReentrantLock:

      • ReentrantLock: provides more control (e.g., try-lock, fairness)
      • synchronized: easier to use but less flexible
    • ForkJoinPool: a pool for tasks that can be broken into smaller subtasks recursively

    • CompletableFuture: used for asynchronous programming.

    Multi-threaded Transaction Processing

    • Use a BlockingQueue for task submission to a thread pool.
    • Use Atomic classes (or StampedLock) for contention minimization.

    Thread-safe Singleton

    • Example implementation of a thread-safe Singleton class in Java

    Spring Framework

    • Annotations:

      • @Component: General stereotype for Spring-managed components
      • @Service: Specifically for business logic/service layer
      • @Repository: Specifically for persistence layer
    • Bean Lifecycle: Instantiation, Dependency Injection, Initialization, Destruction.

    • @Transactional: Manages transactions declaratively, ensuring atomicity and consistency

    REST API Design

    • Use annotations (@RestController, @RequestMapping, @ExceptionHandler, @Valid) for REST API design.
    • Use OAuth2 or JWT for authentication.
    • Implement role-based access control using @PreAuthorize or @Secured.

    Microservices

    • API Gateway: acts as a single entry point for microservices, handling routing, load balancing, and authentication
    • Synchronous vs. Asynchronous Communication:
      • Synchronous: immediate response needed (e.g., REST API)
      • Asynchronous: decoupled communication (e.g., messaging systems like Kafka)
    • Service Discovery: Automatically locates services in a distributed system. Tools: Eureka, Consul, Zookeeper.
    • High Availability: Use load balancers, redundant instances, circuit breakers, and retries.
    • Inter-service Communication: Use REST (synchronous) or message queues (asynchronous)

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Description

    This quiz covers essential design patterns such as Singleton, Prototype, and Factory Method, along with their implementations. It also compares Java's collections, focusing on HashMap and TreeSet, highlighting their characteristics and use cases. Test your knowledge and understanding of these vital software design concepts.

    More Like This

    Use Quizgecko on...
    Browser
    Browser