Sunday, 15 December 2024

Sed command

 

The sed command in Unix is a stream editor used for performing basic text transformations on an input stream (a file or input from a pipeline). It is often used for tasks such as search and replace, deleting lines, inserting lines, and more.

Syntax of sed command

sed [options] 'command' file
  • command: The operation to perform on the input text.
  • file: The file on which sed will operate. If no file is specified, sed reads from standard input (stdin).
  • options: Optional flags that modify sed's behavior.

Common sed Commands and Usage:

1. Search and Replace

The most common use of sed is for search and replace. It uses the syntax:

sed 's/old_text/new_text/' file
  • s/old_text/new_text/: This command searches for old_text and replaces it with new_text.

Example:


sed 's/apple/orange/' fruits.txt

This will replace the first occurrence of the word "apple" with "orange" in each line of fruits.txt


2 .Global Replacement

To replace all occurrences of a pattern in a line, use the g flag:



sed 's/old_text/new_text/g' file

Example:

sed 's/apple/orange/g' fruits.txt
  • This will replace all occurrences of "apple" with "orange" in each line of fruits.txt

Custom Comparator using java8 streams

 



l

Why override equals() and hashCode()?

  • equals(): Determines whether two objects are considered equal. When you add an object to a Set, the set uses this method to check if an object already exists in the set.
  • hashCode(): Provides a hash code that is used for efficient lookups in hash-based collections like HashSet. If you override equals(), you should also override hashCode() to maintain the general contract between these methods.



1 ) import java.util.HashSet;

import java.util.Set;


class Person {

    private String name;

    private int age;


    // Constructor

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }


    // Getters

    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    // Override equals() to compare name and age for equality

    @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        return age == person.age && name.equals(person.name);

    }


    // Override hashCode() to generate a consistent hash code based on name and age

    @Override

    public int hashCode() {

        return 31 * name.hashCode() + Integer.hashCode(age);

    }


    @Override

    public String toString() {

        return "Person{name='" + name + "', age=" + age + '}';

    }

}


public class Main {

    public static void main(String[] args) {

        // Create a Set of Person objects

        Set<Person> people = new HashSet<>();


        // Add some custom objects to the Set

        people.add(new Person("Alice", 30));

        people.add(new Person("Bob", 25));

        people.add(new Person("Alice", 30)); // Duplicate (same name and age)

        people.add(new Person("Charlie", 35));


        // Output the set to see unique objects

        for (Person person : people) {

            System.out.println(person);

        }

    }

}

 


2 )

import java.util.Set;

import java.util.TreeSet;

import java.util.Comparator;


class Person {

    private String name;

    private int age;


    // Constructor

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }


    // Getters

    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    @Override

    public String toString() {

        return "Person{name='" + name + "', age=" + age + '}';

    }

}


public class Main {

    public static void main(String[] args) {

        // Comparator to sort by name in ascending order

        Comparator<Person> nameComparator = (p1, p2) -> p1.getName().compareTo(p2.getName());


        // Create a TreeSet with a custom comparator (sorting by name)

        Set<Person> people = new TreeSet<>(nameComparator);


        // Add some custom objects to the Set

        people.add(new Person("Alice", 30));

        people.add(new Person("Bob", 25));

        people.add(new Person("Charlie", 35));


        // Output the set to see ordered elements

        for (Person person : people) {

            System.out.println(person);

        }

    }

}



3 ) 

import java.util.*;
import java.util.stream.Collectors;

class Person {
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    // Override equals() and hashCode() for unique elements in Set
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        return 31 * name.hashCode() + Integer.hashCode(age);
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> peopleList = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Alice", 30),  // Duplicate
                new Person("Charlie", 35)
        );

        // Using Stream to add unique custom objects to a Set
        Set<Person> uniquePeople = peopleList.stream()
                .collect(Collectors.toSet()); // Collect into a Set to ensure uniqueness

        // Output the unique Set
        uniquePeople.forEach(System.out::println);
    }
}


4 ) 
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> peopleList = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 35)
        );

        // Using Stream to sort by name (custom Comparator)
        List<Person> sortedByName = peopleList.stream()
                .sorted(Comparator.comparing(Person::getName)) // Sorting by name
                .collect(Collectors.toList());

        // Output the sorted list
        sortedByName.forEach(System.out::println);
    }
}

5 ) import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> peopleList = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 35)
        );

        // Using Stream to map Person objects to their names
        List<String> names = peopleList.stream()
                .map(Person::getName) // Map Person to String (name)
                .collect(Collectors.toList());

        // Output the mapped names
        names.forEach(System.out::println);
    }
}

Saturday, 14 December 2024

Find the even and odd numbers using streams and multiply even numbers with 3 and odd one with 2

 

Find the even and odd numbers in list along with multiply even number with 3 and odd number with 

To achieve this using Java 8 Streams, there are multiple ways to process the list of integers, separate the odd and even numbers, and perform the required transformations (multiplying even numbers by 3 and odd numbers by 2

1 )


import java.util.*;

import java.util.stream.*;


public class Main {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);


        List<Integer> result = numbers.stream()

            .map(n -> (n % 2 == 0) ? n * 3 : n * 2) // Multiply even by 3 and odd by 2

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


        System.out.println(result);

    }

}




2 ) import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        List<Integer> result = new ArrayList<>();

        numbers.stream()
            .forEach(n -> {
                if (n % 2 == 0) {
                    result.add(n * 3); // Multiply even by 3
                } else {
                    result.add(n * 2); // Multiply odd by 2
                }
            });

        System.out.println(result);
    }
}


3 )  import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List<Integer> result = numbers.stream()
            .flatMap(n -> Stream.of((n % 2 == 0) ? n * 3 : n * 2)) // FlatMap example
            .collect(Collectors.toList());

        System.out.println(result);
    }
}

4 ) import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List<Integer> result = numbers.stream()
            .mapToInt(n -> (n % 2 == 0) ? n * 3 : n * 2) // Use mapToInt for primitive operations
            .boxed() // Box the result back into Integer
            .collect(Collectors.toList());

        System.out.println(result);
    }
}


5 ) import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        
        Optional<List<Integer>> result = Optional.ofNullable(numbers)
            .filter(list -> !list.isEmpty())
            .map(list -> list.stream()
                .map(n -> (n % 2 == 0) ? n * 3 : n * 2)
                .collect(Collectors.toList()));

        result.ifPresent(System.out::println); // Output the result if present
    }
}

6) import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Map<Boolean, List<Integer>> grouped = numbers.stream()
            .collect(Collectors.groupingBy(n -> n % 2 == 0)); // Group by even or odd

        List<Integer> result = new ArrayList<>();
        
        grouped.get(true).forEach(n -> result.add(n * 3)); // Multiply even by 3
        grouped.get(false).forEach(n -> result.add(n * 2)); // Multiply odd by 2

        System.out.println(result);
    }
}

7 ) 
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List<Integer> result = numbers.stream()
            .collect(Collectors.mapping(n -> (n % 2 == 0) ? n * 3 : n * 2, Collectors.toList()));

        System.out.println(result);
    }
}