Tuesday, 14 January 2025

What are the SOLID principles in object-oriented programming (OOP)

The SOLID principles are a set of five design principles in object-oriented programming (OOP) that help make software designs more understandable, flexible, and maintainable. The acronym SOLID stands for:

  1. S - Single Responsibility Principle (SRP):

    • A class should have only one reason to change, meaning it should have only one job or responsibility. This helps make the system easier to maintain and understand by reducing the complexity of each class.
    • Example: A class that handles both customer data management and logging responsibilities would violate this principle. Instead, you could split the responsibilities into two separate classes: one for customer data and one for logging.
  2. O - Open/Closed Principle (OCP):

    • Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means that you should be able to add new functionality to a class without changing its existing code, typically by using inheritance or interfaces.
    • Example: Instead of modifying a class directly to add a new feature, you could extend the class via a subclass or implement a new interface.
  3. L - Liskov Substitution Principle (LSP):

    • Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. This ensures that derived classes can stand in for their base classes without introducing bugs or unexpected behavior.
    • Example: If a subclass overrides methods of the superclass, the overridden methods should behave in a way that is consistent with the expectations set by the superclass.
  4. I - Interface Segregation Principle (ISP):

    • Clients should not be forced to depend on interfaces they do not use. This principle advocates for creating smaller, more specific interfaces rather than large, general ones that combine multiple responsibilities.
    • Example: Instead of having a single interface with multiple unrelated methods (like IWorker that includes Work and Eat), you could split it into IWorkable and IEatable interfaces, so clients only implement what they need.
  5. D - Dependency Inversion Principle (DIP):

    • High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions. This helps to decouple components and reduce the impact of changes in lower-level details.
    • Example: Instead of a high-level class directly instantiating a low-level class, you can inject dependencies through an interface or abstraction, allowing for greater flexibility in testing and maintenance.

Friday, 3 January 2025

Java 8 Steam API | on Object based operations

 package com.sk.demos;

import java.util.Arrays;

import java.util.List;

import java.util.Optional;

import java.util.stream.Collectors;

public class OperationsOnStundentObject {

public static void main(String[] args) {

List<Student> listStd = Arrays.asList(new Student("ravi", 1, 60), new Student("suri", 2, 80),

new Student("kavi", 3, 90), new Student("mani", 4, 50), new Student("suvi", 5, 70));

                // get list of marks from student object

List<Integer> studentMarks = listStd.stream()

.map(marks -> marks.getMarks())

.collect(Collectors.toList());

System.out.println("studentMarks::" + studentMarks);

                // Finding highest marks using Stream API

System.out.println("\nPrinting the highest marks");

Optional<Integer> highestMarks = listStd.stream()

.map(Student::getMarks) // Mapping to only marks

.max(Integer::compare); // Finding max marks

// Printing the highest marks if present

highestMarks.ifPresent(System.out::println);

// Finding student with highest marks using Stream API

System.out.println("\nFinding student with highest marks");

Optional<Student> highestMarksStudent = listStd.stream()

.max((student1, student2) -> Integer.compare(student1.getMarks(), student2.getMarks()));

highestMarksStudent.ifPresent(System.out::println);

// Sorting by names in ascending order

        System.out.println("\nAscending order based on names:");

                listStd.stream().

sorted((student1,student2)-> student1.getStudenName().compareTo(student2.getStudenName()))

                .forEach(System.out::println);


        // Sorting by names in descending order

        System.out.println("\nDescending order based on names:");

                    listStd.stream()

        .sorted((student1, student2) -> student2.getStudenName().compareTo(student1.getStudenName()))

                .forEach(System.out::println);

}

}

output:
=====================
studentMarks::[60, 80, 90, 50, 70]

Printing the highest marks
90

Finding student with highest marks
Student [studenName=kavi, studentId=3, marks=90]

Ascending order based on names:
Student [studenName=kavi, studentId=3, marks=90]
Student [studenName=mani, studentId=4, marks=50]
Student [studenName=ravi, studentId=1, marks=60]
Student [studenName=suri, studentId=2, marks=80]
Student [studenName=suvi, studentId=5, marks=70]

Descending order based on names:
Student [studenName=suvi, studentId=5, marks=70]
Student [studenName=suri, studentId=2, marks=80]
Student [studenName=ravi, studentId=1, marks=60]
Student [studenName=mani, studentId=4, marks=50]
Student [studenName=kavi, studentId=3, marks=90]

Friday, 13 December 2024

Joining two predicates in stream API using filters

 package com.sk.demos;

import java.util.function.Predicate;

public class JoiningPredicates {

public static void main(String[] args) {

int a[] = { 0, 5, 10, 15, 12, 20, 25, 30 };

//1st predicate will check number is number even or not

//2nd predicate will check number>10

Predicate<Integer> p1 = e -> e % 2 == 0;    

Predicate<Integer> p2 = e -> e > 10;  

for (Integer intCheck : a) {

if (p1.and(p2).test(intCheck)) {

System.out.println(intCheck);

}

}

}

}

output:
===========
12
20
30

Sunday, 8 December 2024

How to remove duplicates in given string? how to Remove duplicates from String using Stream API?

package com.sk.demos;

import java.util.Arrays;

import java.util.Comparator;

import java.util.List;

import java.util.Optional;

import java.util.stream.Collectors;


public class StreamApiTesting {

public static void main(String[] args) { 

        String s="vikatakavi";

       // Using Stream API to remove duplicates

        String removeDuplicates = s.chars()     // Convert string to IntStream (ASCII values)

                                                   .distinct()            // Remove duplicates

                                                   .mapToObj(c -> String.valueOf((char) c)) // Convert back to characters

                                                    .collect(Collectors.joining()); // Collect into a single string

        // Properly formatted output

        System.out.println("Removed duplicates from string: " + removeDuplicates);

    }

}


Output:

===============

Remove duplicates from string: vikat

What is Stream API in java8

Stream API is a newly added feature to the Collections API in Java 8. A stream represents a sequence of elements and supports different operations (Filter, Sort, Map, and Collect) from a collection. Stream API in Java is a toolset for processing sequences of elements in a functional programming style.

Java 8 Features - Steam API Filter | MAP | Sort methods examples

 package com.sk.demos;

import java.util.Arrays;

import java.util.Comparator;

import java.util.List;

import java.util.Optional;

import java.util.stream.Collectors;

public class StreamApiTesting {

    public static void main(String[] args) {

         List<String> list = Arrays.asList("sk", "kr", "ar", "an", "ch", "ra");

System.out.println("Stream api tesing for this list...." + list);

List<String> filterList = list.stream().filter(p -> p.equals("an")).collect(Collectors.toList());

System.out.println("using filter with stream api");

System.out.println(filterList);

System.out.println("========================");

                List<String> mapList = list.stream().map(i -> i.equals("sk") ? (String) "SureshK" : (String) i)

.collect(Collectors.toList());

System.out.println("using map with stream api");

System.out.println(mapList);

System.out.println("========================");

List<Student> listStd = Arrays.asList(new Student("ravi", 1, 60), new Student("suri", 2, 80),

new Student("kavi", 3, 90), new Student("mani", 4, 50), new Student("suvi", 5, 70));

Optional<Student> listStd1 = listStd.stream().max(Comparator.comparing(Student::getMarks));

System.out.println(listStd1.get());

// Sorting students by marks in ascending order

List<Student> sortedByMarksAsc = listStd.stream().sorted(Comparator.comparingInt(Student::getMarks))

.collect(Collectors.toList());

System.out.println("Students sorted by marks (ascending):" + sortedByMarksAsc);

List<Student> sortedByMarksDesc = listStd.stream()

.sorted((s1, s2) -> Integer.compare(s2.getMarks(), s1.getMarks())) // Reverse the order for descending

.collect(Collectors.toList());

System.out.println("Students sorted by marks (descending):" + sortedByMarksDesc);

}

}

Output:

===============

Stream api tesing for this list....[sk, kr, ar, an, ch, ra]

using filter with stream api

[an]

========================

using map with stream api

[SureshK, kr, ar, an, ch, ra]

========================

Student [studenName=kavi, studentId=3, marks=90]


Students sorted by marks (ascending):[Student [studenName=mani, studentId=4, marks=50], Student [studenName=ravi, studentId=1, marks=60], Student [studenName=suvi, studentId=5, marks=70], Student [studenName=suri, studentId=2, marks=80], Student [studenName=kavi, studentId=3, marks=90]]


Students sorted by marks (descending):[Student [studenName=kavi, studentId=3, marks=90], Student [studenName=suri, studentId=2, marks=80], Student [studenName=suvi, studentId=5, marks=70], Student [studenName=ravi, studentId=1, marks=60], Student [studenName=mani, studentId=4, marks=50]]

Friday, 6 December 2024

Stream API using Sort descending order for list

import java.util.*; 

import java.util.stream.*;

  public class SortListDescending

  public static void main(String[] args) {

  // Sample list of strings

List<String> list = Arrays.asList("Su", "Anu", "Aru", "kris");

List<String> sortedList = list.stream()

                                      .sorted(Comparator.reverseOrder())  // Sort using reverse order (descending)

                                      .collect(Collectors.toList());     // Collect the sorted elements into a list

        // Output the sorted list

        System.out.println(sortedList);  

 }

}

Output:

 [kris, Su, Aru, Anu]