Overview
CRUD (Create, Read, Update, Delete) operations are the backbone of most web applications, and with Spring Boot, implementing them has never been easier. In this tutorial, we'll build a simple Spring Boot application that performs CRUD operations using MySQL as our database.
Prerequisites
- JDK 17 or later
- MySQL Server
- Maven
- IDE (e.g., IntelliJ IDEA or Eclipse)
Setup the Spring Boot Project
Begin by setting up a new Spring Boot project using
Spring Initializr or directly from your IDE.
Maven Dependencies
Let's add all the required Maven dependencies to our Spring Boot project. Open the project's pom.xml file and add the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
application.properties
Since we’re using MySQL as our database, we need to configure the URL, username, and password so that our Spring boot can establish a connection with the database on startup.
Open the src/main/resources/application.properties file and add the following properties to it:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
Model Layer
Let's create a package named model. Within this package, we'll define a JPA entity called Employee. This entity will serve as a representation of a domain-specific object that can be mapped to a database table. The class will include fields corresponding to database columns and will use JPA annotations to handle things like primary keys and relationships.
import jakarta.persistence.*;
@Entity
@Table(name = "employees")
public class Employee {
private long id;
private String firstName;
private String lastName;
private String emailId;
public Employee() {
}
public Employee(String firstName, String lastName, String emailId) {
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "email_address", nullable = false)
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
+ "]";
}
}
Repository Layer
Let's create a package named repository. Within this package, let's create an interface called EmployeeRepository. This interface will extend JpaRepository. By doing so, we gain access to a wide array of database operations without having to implement them ourselves. It provides methods for CRUD operations and allows for easy data access and manipulation.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.guides.springboot.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
Custom Exception Layer
Let's create a package named exception. Inside this package, we'll set up a class named ResourceNotFoundException. This class will extend Java's built-in Exception class and will be used to handle custom exception scenarios that are specific to our application. By creating custom exceptions, we gain the ability to provide more descriptive error messages and potentially encapsulate additional data about the error condition.
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception{
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message){
super(message);
}
}
Next, let's create an ErrorDetails class to send the error response back to the client:
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
Next, let's create a
GlobalExceptionHandler class to handle all the exceptions in a single place:
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> globleExcpetionHandler(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Controller Layer
Let's create a package named controller. Within this package, let's create a class called EmployeeController. This controller class serves as an entry point for handling client requests, delegating the processing to appropriate services, and responding back to the client.
We will annotate a controller class with @RestController annotation to create RESTFul web services using Spring MVC.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.guides.springboot.exception.ResourceNotFoundException;
import net.guides.springboot.model.Employee;
import net.guides.springboot.repository.EmployeeRepository;
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
REST Client to REST CRUD REST APIs
When we build RESTful APIs using Spring Boot, we need a way to interact with them to test or consume the services. RestTemplate provides a convenient way to consume web services in a platform-agnostic way.
Let's create a simple client, SpringRestClient, which performs CRUD (Create, Read, Update, Delete) operations on a RESTful service that manages Employee entities.
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import net.guides.springboot.model.Employee;
public class SpringRestClient {
private static final String GET_EMPLOYEES_ENDPOINT_URL = "http://localhost:8080/api/v1/employees";
private static final String GET_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
private static final String CREATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees";
private static final String UPDATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
private static final String DELETE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
private static RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) {
SpringRestClient springRestClient = new SpringRestClient();
// Step1: first create a new employee
springRestClient.createEmployee();
// Step 2: get new created employee from step1
springRestClient.getEmployeeById();
// Step3: get all employees
springRestClient.getEmployees();
// Step4: Update employee with id = 1
springRestClient.updateEmployee();
// Step5: Delete employee with id = 1
springRestClient.deleteEmployee();
}
private void getEmployees() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(GET_EMPLOYEES_ENDPOINT_URL, HttpMethod.GET, entity,
String.class);
System.out.println(result);
}
private void getEmployeeById() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
Employee result = restTemplate.getForObject(GET_EMPLOYEE_ENDPOINT_URL, Employee.class, params);
System.out.println(result);
}
private void createEmployee() {
Employee newEmployee = new Employee("admin", "admin", "admin@gmail.com");
RestTemplate restTemplate = new RestTemplate();
Employee result = restTemplate.postForObject(CREATE_EMPLOYEE_ENDPOINT_URL, newEmployee, Employee.class);
System.out.println(result);
}
private void updateEmployee() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
Employee updatedEmployee = new Employee("admin123", "admin123", "admin123@gmail.com");
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(UPDATE_EMPLOYEE_ENDPOINT_URL, updatedEmployee, params);
}
private void deleteEmployee() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params);
}
}
Conclusion
In this tutorial, we've built a simple Spring Boot application that can perform CRUD operations with a MySQL database. Spring Boot, combined with Spring Data JPA and MySQL, provides a powerful toolkit for building robust web applications quickly and efficiently. Happy coding!
Related Java Source Code Examples:
Java Record Class Example
Java Text Blocks Example
Java Record Builder Pattern Example
Java Record Constructor Example
Java Record Constructor Validation Example
Java Record Serializable Example
Java Record Getter Example
Java Record Default Constructor
Java Records CRUD (Create, Read, Update, Delete) Example
Java Record Custom Methods
Java Record Custom toString
Java Record Custom equals and hashCode
Java Records with Spring Boot CRUD Example
Java Record Implement Interface Example
Java Switch Expressions Example
Java Pattern Matching for instanceof
Java Sealed Class Example
Java Sealed Class vs Final Class
Java Sealed Class Record Example
Java Sealed Class Generic Example
Java Sealed Class Enum Example
Java Sealed Class Switch Example
Java var Keyword Example
Java CompactNumberFormat Class Example
Java Vector API Example
Pattern Matching for Switch Example
Collectors.teeing() in Stream API Example
Java FileSystems.newFileSystem() Method Example
Java Files.readString() and Files.writeString() Example
Java String isBlank Example
Java String strip Example
Java String repeat Example
Java String lines Example
Java String stripIndent Example
Java Binary Search (Recursive and Iterative) Program
Java Happy Birthday Program
Java Program That Calculates the Age of a Person
Java Logical And Or Xor Examples
Java Format Date and Time Examples
Java Convert String to Date and Time
Java Convert Roman to Integer Number
Java Convert Octal to HexaDecimal
Java Convert Octal to Decimal
Java Convert Integer Number to Roman Number
Java Convert Hexadecimal to Binary
Java Convert Decimal to Octal
Java Convert Decimal to Binary
Java Convert Binary to Decimal
Java Convert Binary to an Octal
Java Convert Binary to a Hexadecimal
Java Convert a Unix Timestamp to Date Time
Java Check If Two Integer Arrays are Equals
Java program that removes all white spaces from the given string
Java 8 program that counts the number of vowels and consonants in a given string
Java 8 program that reverses words of a given string
Java Program to Count Number of Digits in an Integer
Java Program Fibonacci Series Using Recursion
Java Program to Find Factorial of a Number
Java program to calculate the area of Triangle
Java Program to Calculate Area of Square
Java Program to Calculate Area of Rectangle
Java Program to find the Smallest of three numbers using Ternary Operator
Java Program to Find Largest of Three Numbers
Java Program to Find GCD of Two Numbers
Java Program to Check Armstrong Number
Java Program to Generate Random Number
Java Program to Check if Number is Positive or Negative
Java program to check prime number
Java Program to Calculate Simple Interest
Java Program to Swap Two Numbers Without using a Temporary Variable
Java Program to Swap Two Numbers
Java Program to Find ASCII Value of a Character
Java Program to Check Whether an Alphabet is Vowel or Consonant
Java Program to Check Leap Year
Java Program to Check Even or Odd Number
Java Program to Add Two Numbers
Java Program to Swap Two Strings Without Using Third Variable
Java Program to Swap Two Strings with Third Variable
How to Get All Digits from String in Java
Find Duplicate Number in Array in Java
How to Get Current Working Directory in Java?
Check Palindrome String in Java
Java Program to Create Pyramid Of Numbers
Create a String object in Java Example
Java String valueOf() Method Example
Java String.trim() Method Example
Java String.toUpperCase() Method Example
Java String toLowerCase() Method Example
Java String toCharArray() Method Example
Java String substring() Method Example
Java String.startsWith() Method Example
Java String split() Method Example
Java String.replaceFirst() Method Example
Java String.replaceAll() Method Example
Java String replace() Method Example
Java String regionMatches() Method Example
Java String length() Method Example
Java String lastIndexOf() Method Example
Java String intern() Method Example
Java String indexOf() Method Example
Java String getChars() Method Example
Java String getBytes() Method Example
Java String equals() and equalsIgnoreCase() Example
Java String.endsWith() Method Example
Java String.contentEquals() Method Example
Java String.contains() Method Example
Java String concat() Method Example
What's the Simplest Way to Print a Java Array?
Merge two String Arrays Example
Checks If a String is Not Empty and Not Null in Java
Reverse a String in Java Using StringBuilder
Capitalize the First Letter of a String in Java Example
Java String codePointAt() Method Example
Java String Compare Using equals() Method
Sort String in Descending Order in Java
Sort String in Ascending Order in Java
How to Get All Digits from String in Java
Java String getDigits() Utility Method
Java String isAlphanumeric() Utility Method
Java String isAlpha() Utility Method
Java String countMatches() Utility Method
Java String mergeStringArrays(String array1[], String array2[]) Utility Method Example
Java String quote( String str) Utility Method
Java arrayToMap(String[][] array) Utility Method
Java String fromBufferedReader() Utility Method - Converts a BufferedReader into a String
Java String isNumericSpace() Utility Method
Java String isNumeric() Utility Method
Java String isAlphanumericSpace() Utility Method
Java String isAlphaSpace(() Utility Method
Java trimArrayElements() Utility Method
Java trimArrayElements() Utility Method
Java String containsWhitespace() Utility Method
Java String isBlank() Utility Method
Java String isAnyEmpty() Utility Method
Java String isNotEmpty() Utility Method
Java String isEmpty() Utility Method
Java String Uppercase First Character Example
Java String uppercaseFirstChar() Utility Method
Java String trimTrailingCharacter() Utility Method
Java String trimLeadingCharacter() Utility Method
Java String trimTrailingWhitespace() Utility Method
Java String trimLeadingWhitespace() Utility Method
Java String trimAllWhitespace() Utility Method
Java String trimWhitespace() Utility Method
Java StringBuilder trimToSize() Method Example
Java StringBuilder substring() Method Example
Java StringBuilder setLength() Method Example
Java StringBuilder reverse() Method Example
Java StringBuilder lastIndexOf() Method Example
Java StringBuilder insert() Method Example
Java StringBuilder indexOf() Method Example
Java StringBuilder getChars() Method Example
Java StringBuilder ensureCapacity() Method Example
Java StringBuilder deleteCharAt() Method Example
Java StringBuilder delete() Method Example
Java StringBuilder codePointBefore() Method Example
Java StringBuilder codePointAt Method Example
Java StringBuilder capacity() Method Example
Java StringBuilder append() Method Example
Java Convert Integer to String Example
Java Convert Float to String Example
Java Convert Double to String Example
Java Convert Short to String Example
Java Convert Long to String Example
Java Convert Character to String Example
Java Convert Byte to String Example
Java Convert Boolean to String Example
Java Convert String To Short Example
Java Convert String To Long Example
Java Convert String To Integer Example
Java Convert String To Float Example
Java Convert String To Double Example
Java Convert String To Byte Example
Java Convert String To Boolean Example
Clear ArrayList in Java Example
Java ArrayList add(), get() and set() Method Example
Iterate over ArrayList Using forEach Java
Iterate over ArrayList using Iterator in Java
Java ArrayList indexOf() and lastIndexOf() Example
Search an Element in an ArrayList in Java
Java ArrayList removeAll() Method Example
Java ArrayList remove() Method Example
How to Iterate over ArrayList in Java
How to Remove Element from ArrayList in Java
How to Access Elements of ArrayList in Java
Create ArrayList from Another ArrayList in Java
How to Create an ArrayList and Add Elements to It
Java ArrayList subList() Example
Get Index of Elements in ArrayList Example
Java ArrayList removeIf() Example
Copying part of Array in Java Example
Sorting an Array using Arrays.sort() Method
Check Two Arrays are Deeply Equal
Java Arrays.copyOf() Example - Copying an Array
Java Arrays.binarySearch() Example - Searching an Array
Java Arrays.asList() Example - Convert Array to ArrayList
Sort String in Ascending Order in Java
Sort String in Descending Order in Java
Sort Integer in Ascending Order in Java Example
Sort Integer in Descending Order in Java Example
Sort User-Defined Objects in Ascending Order in Java
Sort User-Defined Objects in Descending Order in Java
Sort User-Defined Objects using Comparator Interface
Java LinkedList add(), addFirst(), addLast() and addAll() Example
Iterate LinkedList using forEach() Method Example
Iterate through a LinkedList using an Iterator in Java
Iterate or Loop Through Elements LinkedList in Java Example
Search Elements of LinkedList in Java with Example
Remove First and Last Elements of LinkedList in Java
Get Elements from LinkedList Java Example
Java LinkedList remove(), removeFirst(), removeLast(), removeIf() and clear() Example
Create HashSet in Java
Iterating over a HashSet using Iterator
Iterate over HashSet in Java
Remove Element from HashSet in Java
Create HashSet in Java
Iterating over a LinkedHashSet using forEach() Method Example
Iterate over LinkedHashSet using Iterator in Java Example
Iterate over LinkedHashSet in Java Example
Remove all Elements from LinkedHashSet in Java Example
Remove Element from LinkedHashSet Example
Check If an Element Exists in Java LinkedHashSet Example
Create LinkedHashSet in Java Example
Create TreeSet in Java Example
Iterating over a TreeSet using Java 8 forEach() Method
Iterate over a TreeSet using Iterator in Java Example
Iterate over TreeSet in Java Example
Remove All Elements from Java TreeSet Example
Remove First and Last Element from TreeSet in Java
Remove Element from TreeSet in Java Example
Check If an Element Exists in Java TreeSet Example
Java TreeSet add(), first() and last() Method Example
Java Convert ArrayList to Stack Example
Java Convert Array to Stack Example
Java Stack push() Method Example
Java Stack empty() Method Example
Java Stack peek() Method Example
Java Stack search() Method Example
Java Stack pop() Method Example
Java Deque and ArrayDeque Examples
Iterating over a Queue in Java Example
Java Queue isEmpty(), size(), element() and peek() Example
Java Queue Interface Example
Java Priority Queue of User Defined Objects Example
Java Create a Priority Queue with a Custom Comparator
Create a Priority Queue in Java Example
HashMap Stream and Filtering Example
Java HashMap Iteration over Values Example
Java HashMap Iteration over Keys
Java HashMap replace() Example
Java HashMap size Example
Iterate over a HashMap Java using Lambda
Iterate over a HashMap Java 8 forEach
Iterating over a HashMap using Iterator in Java
Iterate over HashMap in Java
How to Store Employee Objects in HashMap
Remove Entry from HashMap Java
Check If Value Exists in HashMap Java Example
Check If Key Exists in HashMap Java Example
Create a HashMap in Java Example
How to Delete Data from MySQL Table using Java
How to Insert Data in MySQL Table using Java
How to Create Database Table in Java
JDBC DriverManager Example
JDBC PreparedStatement Example
JDBC Statement Example
Java MySQL DataSource Example
Update Query in MySQL using Java PreparedStatement
Login Example with JSP + Servlet + JDBC + MySQL Database
JSP + JDBC + MySQL Example Tutorial
JSP Form Example with JDBC and MySQL Database
Java JDBC CRUD Example - SQL Insert, Select, Update, and Delete Examples
Java Swing JDBC MySQL Database Example
Java JDBC Connection to HSQLDB Database
JDBC Connection to H2 Database Example
JDBC Connection to PostgreSQL Example
JDBC Connection to Oracle Database Example
JDBC Transaction Management Example
JDBC Delete Query Example
JDBC Select Query Example
JDBC Update Query Example
JDBC Insert Multiple Rows Example
JDBC Create a Table Example
What are different types of JDBC Drivers
Advantages of Hibernate Framework over JDBC
Java PostgreSQL Example
Java H2 Insert Record Example
Java H2 Embedded Database Example
Java H2 Create Table Example
Java Simple Lambda Expression Example
Java Lambda Expressions Multiple Statements
Java Lambda Expressions forEach Example
Java Lambda Expression with Multiple Parameters Example
Java Lambda Expression Runnable Example
Java Lambda Expression Comparator Example
Refactoring Factory Design Pattern with Lambdas
Refactoring Chain of Responsibility Pattern with Lambdas
Refactoring Observer Design Pattern with Lambdas
Refactoring Strategy Design Pattern with Lambdas
Iterate HashMap with forEach() + Lambda Expression Example
Iterate HashSet with forEach() + Lambda Expression Example
Iterate ArrayList with forEach() + Lambda Expression Example
Java method reference to a constructor example
Java method reference to static method example
Java method reference to an instance method of an object example
Java method reference to an instance method of an arbitrary object of a particular type
Java 8 - Create Stream Object from Arrays Example
Java 8 Creating a Stream from an Array
Java 8 - Create Stream Object from Collection, List, Set
Java 8 Stream - Sort List of String objects in Descending Order Example
Java 8 Stream - Sort List of String objects in Ascending Order Example
How to convert a Java 8 Stream to an Array?
Java 8 Stream - allMatch(),anyMatch() and noneMatch() Example
Java 8 Stream - Sort List of Objects by Multiple Fields
Java 8 Stream - Sort List of Custom Objects in Ascending and Descending Order
Java 8 - Stream filter(), forEach(), collect() and Collectors.toList() Example
Java Stream filter null values example
Java Stream filter map by values example
Java Stream filter map by keys example
Java 8 Collectors.counting() Example
Java 8 Collectors.averagingDouble() Example
Java 8 Collectors.toSet() Example
Java 8 Collectors.toList() Example
Java 8 Collectors.joining() example
Java 8 Stream multiple filter operations
Java 8 Stream filter map by keys
Java 8 Stream filter map by values
Java 8 Stream collect to list example
Java 8 Stream Collectors.counting() exmaple
Java 8 Collectors.collectingAndThen() example
Java 8 Collectors.toList() Example
Java 8 Collectors.minBy() and Collectors.maxBy() example
Java Stream filter() Example
Java Stream map() Example
Java Stream flatMap() Example
Java Stream distinct() Example
Java Stream limit() Example
Java Stream peek() Example
Java Stream anyMatch() Example
Java Stream allMatch() Example
Java Stream noneMatch() Example
Java Stream collect() Example
Java Stream count() Example
Java Stream findAny() Example
Java Stream findFirst() Example
Java Stream forEach() Example
Java Stream min() Example
Java Stream max() Example
Java Stream reduce() Example
Java Stream toArray() Example
Java Function Functional Interface Example
Java Supplier Functional Interface Example
Java Consumer Example
Java BiConsumer Example
Java BiFunction Example
Java Predicate Example
Java 8 LongConsumer Example
Java 8 IntConsumer Example
Java 8 DoubleConsumer Example
Java StringJoiner Example
Create Optional Class Object in Java - empty(), of(), ofNullable() Methods
Optional get() Method - Get Value from Optional Object in Java
Optional isPresent() Method Example
Optional orElse() Method Example
Optional orElseGet() Method Example
Optional orElseThrow() Method Example
Optional filter() and map() Method Examples
Java 8 program that counts the number of vowels and consonants in a given string
Java 8 program that reverses words of a given string
Java 8 - Copy List into Another List Example
Check Whether the Given Year is Leap Year or Not in Java
Java 8 forEach() Array Example
Java 8 forEach() Map Example
Java 8 forEach() Set Example
Java 8 forEach() List Example
Getting current date and time with Clock
Convert LocalDate to Date in Java
Convert LocalDateTime into Date in Java
Connvert java.util.Date to java.time.LocalDateTime Example
Convert java.util.Date to java.time.LocalDate Example
Duration Between Two LocalDate in Java
Java Convert ZonedDateTime to String Example
Convert String to ZonedDateTime in Java
Compare ZonedDateTime Objects in Java
How to Get Hour, Minute, Second from ZonedDateTime in Java
Convert ZonedDateTime to LocalTime Example
Convert ZonedDateTime to LocalDateTime in Java
Java ZonedDateTime now() and of() Method Example
Convert LocalDateTime to LocalTime in Java
Convert LocalDateTime to LocalDate in Java
Compare LocalDateTime Objects in Java
Java LocalDateTime - Get Hour, Minute and Second
How to Get Day Month and Year from LocalDateTime in Java
Java LocalDateTime now() Method Example
How to Get Current Date Time in Java
Convert LocalDate to String in Java
Convert String to LocalDate in Java
Java LocalDate isLeapYear() Method Example
How to Get Number of Days from Month and Year using LocalDate in Java
Compare Java LocalDate Objects Example
How to Add Days Weeks Months and Years to LocalDate in Java
How to get Day Month and Year from LocalDate in Java
Java LocalDate now() Method Example - Get Current Date and Specific Date
Convert LocalTime to String in Java
Convert String to LocalTime in Java
Java LocalTime isBefore() and isAfter() Method Example
How to Compare Time in Java
Java 8 - LocalTime getHour(), getMinute(), getSecond() and getNano() Example
Java LocalTime now() Method Example - Get Current Time and Specific Time
Java 8 Get Local Date Time in All Available Time Zones
How to get year, month, day, hours, minutes, seconds and milliseconds of LocalDateTime in Java 8?
How to get year, month, day, hours, minutes, seconds and milliseconds of Date in Java?
Difference between Two Dates in Java
Create LocalDateTime from LocalDate and LocalTime in Java
Java
MySQL
Spring Boot 3
Comments
Post a Comment