{{theTime}}

Search This Blog

Total Pageviews

MongoDB Tutorial

MongoDB Tutorial

Table of Contents

Introduction to MongoDB

MongoDB is a popular open-source NoSQL database that provides high performance, high availability, and automatic scaling.

Installation

To install MongoDB, follow the instructions provided in the official MongoDB documentation.

Creating a Database


use mydatabase

Creating a Collection


db.createCollection("mycollection")

Inserting Data


db.mycollection.insertOne({
  name: "John Doe",
  age: 30,
  email: "john@example.com"
})

Querying Data


db.mycollection.find()

Updating Data


db.mycollection.updateOne(
  { name: "John Doe" },
  { $set: { age: 35 } }
)

Deleting Data


db.mycollection.deleteOne({ name: "John Doe" })

Sorting Algorithms

Sorting Algorithms

Bubble Sort

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

  • Time Complexity:
    • Best Case: O(n)
    • Worst Case: O(n^2)
    • Average Case: O(n^2)
  • Space Complexity: O(1)

Selection Sort

Selection Sort is an in-place comparison sorting algorithm that divides the input list into two parts: a sorted sublist and an unsorted sublist.

  • Time Complexity:
    • Best Case: O(n^2)
    • Worst Case: O(n^2)
    • Average Case: O(n^2)
  • Space Complexity: O(1)

Insertion Sort

Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time.

  • Time Complexity:
    • Best Case: O(n)
    • Worst Case: O(n^2)
    • Average Case: O(n^2)
  • Space Complexity: O(1)

Merge Sort

Merge Sort is a divide-and-conquer algorithm that divides the input array into two halves, sorts each half separately, and then merges them.

  • Time Complexity:
    • Best Case: O(n log n)
    • Worst Case: O(n log n)
    • Average Case: O(n log n)
  • Space Complexity: O(n)

Quick Sort

Quick Sort is a divide-and-conquer algorithm that selects a 'pivot' element from the array and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot.

  • Time Complexity:
    • Best Case: O(n log n)
    • Worst Case: O(n^2)
    • Average Case: O(n log n)
  • Space Complexity: O(log n)
Java Sequenced Collection

Java Sequenced Collection

The Sequenced Collection feature was introduced in Java 9.

Purpose

The purpose of Sequenced Collection is to provide a way to create collections that maintain the order of elements based on the order in which they were added.

Real-time Use Case

Imagine a scenario where you need to maintain the order of tasks in a to-do list application. You want to display the tasks in the order they were added by the user.

In this case, you can use a Sequenced Collection to store the tasks, ensuring that they are displayed in the correct order.

Executable Code


import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Example using SequencedMap
        System.out.println("Example using SequencedMap:");
        Map<String, String> sequencedMap = new SequencedMap<>();
        sequencedMap.put("1", "One");
        sequencedMap.put("2", "Two");
        sequencedMap.put("3", "Three");

        System.out.println("Entries in the order they were added:");
        for (Map.Entry<String, String> entry : sequencedMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Example using SequencedSet
        System.out.println("\nExample using SequencedSet:");
        Set<String> sequencedSet = new SequencedSet<>();
        sequencedSet.add("Apple");
        sequencedSet.add("Banana");
        sequencedSet.add("Orange");

        System.out.println("Elements in the order they were added:");
        for (String element : sequencedSet) {
            System.out.println(element);
        }
    }
}
        
Java Virtual Threads

Java Virtual Threads

Java Virtual Threads, introduced in Java 21 (JDK 18), are lightweight threads managed by the Java Virtual Machine (JVM). Unlike traditional OS threads, virtual threads are managed entirely within the JVM, providing a more efficient and scalable concurrency model.

What are Java Virtual Threads?

Java Virtual Threads are threads that are managed by the JVM itself, rather than relying on the underlying operating system's threading mechanism. They are lightweight and consume significantly less memory compared to traditional OS threads.

When were Java Virtual Threads introduced?

Java Virtual Threads were introduced in Java 21, which is part of JDK 18. They are a major feature introduced to enhance the concurrency model of the Java platform.

Use Cases for Java Virtual Threads

  • Highly Concurrent Applications: Virtual threads are suitable for applications that require high levels of concurrency, such as web servers and microservices.
  • Asynchronous I/O Operations: They are well-suited for handling asynchronous I/O operations, such as network communication and file I/O.
  • Task Parallelism: Virtual threads can be used to parallelize tasks across multiple CPU cores, improving performance on multi-core systems.
  • Scalability: Applications that need to scale to a large number of concurrent users or connections can benefit from the lightweight nature of virtual threads.

Implementation Code

Here's an example of how to create and use virtual threads in Java:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VirtualThreadExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newVirtualThreadExecutor();

        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                System.out.println("Executing task on virtual thread: " + Thread.currentThread().getName());
            });
        }

        executor.shutdown();
    }
}

In this example, we create a virtual thread executor using Executors.newVirtualThreadExecutor() and submit tasks to it using the execute() method. Each task is executed on a separate virtual thread.

Java 21 Features

Java 21 Features


Switch Expressions

Java 21 introduces a simplified syntax for switch statements, allowing them to be used as expressions. This enables more concise and readable code.

Example Code:

int day = 3;
String dayType = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> throw new IllegalArgumentException("Invalid day: " + day);
};
System.out.println("Day type: " + dayType);

Pattern Matching for instanceof

Java 21 introduces pattern matching for the instanceof operator, allowing for more concise and readable code when working with object types.

Example Code:

Object obj = "Hello";
if (obj instanceof String s) {
    System.out.println("Length of string: " + s.length());
} else {
    System.out.println("Not a string");
}

Records

Java 21 introduces record classes, which are a concise way to declare classes that are essentially data carriers, automatically generating constructors, accessors, and equals() and hashCode() methods.

Example Code:

public record Person(String name, int age) {
    // Record class automatically defines:
    // - Constructor
    // - Accessor methods
    // - equals() and hashCode() methods
}

Text Blocks

Java 21 introduces text blocks, which allow for multiline string literals without the need for escape characters. This improves readability and maintainability of code.

Example Code:

String html = """
              <html>
              <body>
              <p>Hello, world!</p>
              </body>
              </html>
              """;
System.out.println(html);

Sealed Classes

Java 21 introduces sealed classes, which restrict the subclasses that can extend or implement them, providing more control over class hierarchies.

Example Code:

public sealed interface Shape permits Circle, Rectangle, Triangle {
    // Interface definition
}

Local Interfaces

Java 21 allows the declaration of interfaces within methods, known as local interfaces. This can be useful for encapsulating functionality within a method.

Example Code:

public void process() {
    interface Callback {
        void onSuccess();
        void onFailure();
    }
    // Local interface usage
}

graphql spring boot error java.lang.IllegalArgumentException:

Error: java.lang.IllegalArgumentException: Name for argument of type [java.lang.String] not specified, and parameter name information not found in class file either.

Fix: Change @Argument decorator by adding the required input String.

MongoDB Tutorial MongoDB Tutorial Table of Contents Introduction to MongoDB Installation Creating a Database Creati...