├── ArraysDemo ├── ArraysAndCollectionTasks.java ├── ArraysCollectionREADME.md ├── ArraysCollectionsDemo.java ├── Demo.java └── Employee.java ├── Cloning ├── DeepShallowDemo.java └── Main.java ├── Java8 ├── pom.xml └── src │ └── main │ └── java │ ├── ComparatorDemo.java │ ├── DateTime.md │ ├── LinkedHashMapDemo.java │ ├── Optionals │ ├── OptionalCodeDemo.java │ ├── OptionalDemo.java │ └── OptionalREADME.md │ ├── Person.java │ ├── README-Comparators.md │ ├── README-Streams.md │ ├── StreamsAllCodeSolutions.java │ ├── StreamsCodeDemoPart2.java │ ├── StreamsPart2.java │ ├── StreamsPart2_Array.java │ ├── Student.java │ └── assets │ └── Screenshot 2023-07-27 at 11.07.16 PM.png ├── LambdasAndStreams └── src │ └── main │ └── java │ └── StreamsCodePart2 ├── OverridingConcepts └── StaticMethodDemo.java └── README.md /ArraysDemo/ArraysAndCollectionTasks.java: -------------------------------------------------------------------------------- 1 | //import java.util.*; 2 | // 3 | //public class ArraysAndCollectionTasks { 4 | // 5 | // public static void main(String[] args) { 6 | // // Question 1: Sorting an Array of Integers 7 | // int[] array1 = {3, 1, 4, 1, 5, 9, 2, 6}; 8 | // Arrays.sort(array1); // Sorting student scores in ascending order to determine their ranking. 9 | // System.out.println("Sorted Array: " + Arrays.toString(array1)); 10 | // 11 | // // Question 2: Checking for Equality of Two Arrays 12 | // int[] array2 = {1, 2, 3}; 13 | // boolean equal = Arrays.equals(array1, array2); // Verifying if two sets of user-selected preferences are identical to avoid redundant processing. 14 | // System.out.println("Are arrays equal? " + equal); 15 | // 16 | // // Question 3: Finding the Maximum Element in an ArrayList 17 | // ArrayList list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6)); 18 | // int max = Collections.max(list); // Determining the highest temperature recorded in a week to provide a weather summary. 19 | // System.out.println("Maximum element in ArrayList: " + max); 20 | // 21 | // // Question 4: Shuffling Elements of an ArrayList 22 | // Collections.shuffle(list); // Randomizing the order of multiple-choice questions in an online quiz to prevent cheating. 23 | // System.out.println("Shuffled ArrayList: " + list); 24 | // 25 | // // Question 5: Finding the Frequency of an Element in an ArrayList 26 | // int frequency = Collections.frequency(list, 1); // Analyzing customer purchase history to identify frequently bought items for targeted marketing. 27 | // System.out.println("Frequency of '1' in ArrayList: " + frequency); 28 | // 29 | // // Question 6: Checking if an ArrayList is Empty 30 | // boolean isEmpty = list.isEmpty(); // Validating if a shopping cart is empty before allowing the checkout process. 31 | // System.out.println("Is ArrayList empty? " + isEmpty); 32 | // 33 | // // Question 7: Converting Array to ArrayList 34 | // String[] array3 = {"apple", "banana", "orange"}; 35 | // ArrayList arrayList = new ArrayList<>(Arrays.asList(array3)); // Transforming an array of user input into a dynamic list for further manipulation in a contact management application. 36 | // System.out.println("ArrayList from Array: " + arrayList); 37 | // 38 | // // Question 8: Reversing an Array 39 | // Collections.reverse(Arrays.asList(array3)); // Displaying historical transaction records in reverse chronological order for financial analysis. 40 | // System.out.println("Reversed Array: " + Arrays.toString(array3)); 41 | // 42 | // // Question 9: Removing All Occurrences of an Element from an ArrayList 43 | // list.removeAll(Collections.singleton(1)); // Filtering spam emails by removing blacklisted words from an inbox. 44 | // System.out.println("ArrayList after removing all occurrences of '1': " + list); 45 | // 46 | // // Question 10: Copying Elements from ArrayList to Array 47 | // Integer[] array4 = list.toArray(new Integer[0]); // Exporting a list of contact names from an address book to a legacy system that only accepts arrays. 48 | // System.out.println("Copied Array: " + Arrays.toString(array4)); 49 | // 50 | // // Question 11: Removing Null Values from an ArrayList 51 | // ArrayList stringList = new ArrayList<>(Arrays.asList("apple", null, "banana", null, "orange")); 52 | // stringList.removeAll(Collections.singleton(null)); // Cleaning up a dataset by eliminating records with missing or null values before performing statistical analysis. 53 | // System.out.println("List after removing null values: " + stringList); 54 | // 55 | // // Question 12: Finding the Average of an Array 56 | // int[] numbers = {1, 2, 3, 4, 5}; 57 | // double average = Arrays.stream(numbers).average().orElse(Double.NaN); // Calculating the average daily traffic volume on a particular road segment to optimize traffic flow. 58 | // System.out.println("Average of the array: " + average); 59 | // 60 | // // Question 13: Checking for Palindromes in an ArrayList 61 | // ArrayList wordList = new ArrayList<>(Arrays.asList("radar", "apple", "level", "banana")); 62 | // for (String word : wordList) { 63 | // boolean isPalindrome = new StringBuilder(word).reverse().toString().equalsIgnoreCase(word); // Validating if a list of passwords generated by a password manager contains any palindromes to improve security. 64 | // System.out.println(word + " is a palindrome: " + isPalindrome); 65 | // } 66 | // Collections.reverse(); 67 | // 68 | // // Question 14: Sorting a List of Strings in Reverse Order 69 | // List strList = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "grape")); 70 | // Collections.sort(strList, Collections.reverseOrder()); // Sorting a list of employee names in reverse alphabetical order to generate a descending employee directory. 71 | // System.out.println("List of strings sorted in reverse order: " + strList); 72 | // 73 | // // Question 15: Finding the Index of the Last Occurrence of an Element in a List 74 | // int lastIndex = Collections.lastIndexOfSubList(strList, Arrays.asList("apple", "banana")); // Locating the most recent entry of a particular product in an inventory management system. 75 | // System.out.println("Index of the last occurrence of sublist: " + lastIndex); 76 | // 77 | // Collections. 78 | // // Question 16: Creating an Unmodifiable List 79 | // List unmodifiableList = Collections.unmodifiableList(Arrays.asList(1, 2, 3, 4, 5)); 80 | // System.out.println("Unmodifiable List: " + unmodifiableList); // Providing a read-only view of a list of product features to users in a software documentation. 81 | // 82 | // // Question 17: Creating a Synchronized List 83 | // List synchronizedList = Collections.synchronizedList(new ArrayList<>()); 84 | // synchronizedList.add("one"); 85 | // synchronizedList.add("two"); 86 | // synchronizedList.add("three"); 87 | // System.out.println("Synchronized List: " + synchronizedList); // Managing access to a shared list of tasks among multiple threads in a multi-user task management system. 88 | // } 89 | //} 90 | -------------------------------------------------------------------------------- /ArraysDemo/ArraysCollectionREADME.md: -------------------------------------------------------------------------------- 1 | Sure, here's the updated README file: 2 | 3 | --- 4 | 5 | # Arrays and Collections Utility Class 6 | 7 | ## Overview 8 | 9 | The Arrays and Collections Utility Class in Java provides a set of static methods to perform common operations on arrays and collections efficiently. These methods encapsulate common functionalities to simplify code and improve readability. 10 | 11 | ## Features 12 | 13 | The utility class offers the following features: 14 | 15 | - **Sorting Arrays**: Sort arrays of primitives or objects in ascending or descending order using the `Arrays.sort()` method. 16 | - **Converting Arrays to Collections**: Convert arrays to ArrayLists or other collection types using the `Arrays.asList()` method. 17 | - **Manipulating Collections**: Perform various operations on collections like shuffling, reversing, and removing duplicates using methods from the `Collections` class. 18 | - **Finding Elements**: Find minimum, maximum, and average elements in collections using methods from the `Collections` class. 19 | - **Frequency and Occurrence**: Calculate the frequency of elements or find the last occurrence of an element using methods from the `Collections` class. 20 | - **Checking Properties**: Check if a collection is empty or contains null values using methods from the `Collections` class. 21 | - **Immutable and Synchronized Collections**: Create unmodifiable or synchronized views of collections using methods from the `Collections` class. 22 | 23 | ## Code Snippets 24 | 25 | ### Sorting an Array: 26 | 27 | ```java 28 | import java.util.Arrays; 29 | 30 | int[] array = {3, 1, 4, 1, 5, 9, 2, 6}; 31 | Arrays.sort(array); 32 | System.out.println("Sorted Array: " + Arrays.toString(array)); 33 | ``` 34 | 35 | ### Converting Array to ArrayList: 36 | 37 | ```java 38 | import java.util.ArrayList; 39 | import java.util.Arrays; 40 | 41 | int[] array = {3, 1, 4, 1, 5, 9, 2, 6}; 42 | ArrayList arrayList = new ArrayList<>(Arrays.asList(array)); 43 | System.out.println("ArrayList from Array: " + arrayList); 44 | ``` 45 | 46 | ### Finding Maximum Element in ArrayList: 47 | 48 | ```java 49 | import java.util.ArrayList; 50 | import java.util.Collections; 51 | 52 | ArrayList arrayList = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6)); 53 | int max = Collections.max(arrayList); 54 | System.out.println("Maximum element in ArrayList: " + max); 55 | ``` 56 | 57 | ## Contribution 58 | 59 | Contributions to this utility class are welcome! If you have additional functionalities or improvements to suggest, feel free to submit a pull request or open an issue on the GitHub repository. 60 | 61 | ## License 62 | 63 | This utility class is provided under the [MIT License](LICENSE). 64 | 65 | --- 66 | 67 | Feel free to adjust the content or add more code snippets to showcase additional functionalities of your utility class! -------------------------------------------------------------------------------- /ArraysDemo/ArraysCollectionsDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | public class ArraysCollectionsDemo { 7 | 8 | public static void main(String[] args) { 9 | // Question 1: Sorting an Array of Integers 10 | int[] arr1 = {3,7,8,1,5,9}; 11 | Arrays.sort(arr1); 12 | System.out.println(Arrays.toString(arr1)); 13 | 14 | // Question 2: Checking for Equality of Two Arrays 15 | //user preferences of 2 diff users - equal? 16 | int[] arr2 = { 6,2,1}; 17 | System.out.println("is equal? "+ Arrays.equals(arr1, arr2)); 18 | 19 | 20 | // Question 3: Finding the Maximum Element in an ArrayList 21 | ArrayList list1 = new ArrayList<>(Arrays.asList(2, 7, 3, 1, 2, 9, 2, 5)); 22 | System.out.println("max element "+ Collections.max(list1)); 23 | 24 | // Question 4: Shuffling Elements of an ArrayList 25 | //quiz app - randomise the questions 26 | 27 | Collections.shuffle(list1); 28 | System.out.println("shuffled list "+list1); 29 | // Question 5: Finding the Frequency of an Element in an ArrayList 30 | 31 | int freq = Collections.frequency(list1, 2); 32 | System.out.println("frequency = "+ freq); 33 | 34 | // Question 7: Converting Array to ArrayList 35 | String[] fruits = {"apple", "pineapple","cherry" ,"banana", "grapes", "cherry" ,"banana"}; 36 | ArrayList fruitsList = new ArrayList<>(Arrays.asList(fruits)); 37 | System.out.println("fruits "+ fruitsList); 38 | // 39 | // // Question 8: Reversing an Array 40 | // Collections.reverse(Arrays.asList(fruits)); 41 | // System.out.println(Arrays.toString(fruits)); 42 | // 43 | // // Question 9: Removing All Occurrences of an Element from an ArrayList 44 | // list1.removeAll(Collections.singleton(2)); 45 | // System.out.println(list1); 46 | // 47 | // // Question 10: Copying Elements from ArrayList to Array 48 | // Integer[] arrList = list1.toArray(new Integer[0]); 49 | // System.out.println("copied array "+Arrays.toString(arrList)); 50 | // 51 | // 52 | // // Question 11: Removing Null Values from an ArrayList 53 | // ArrayList stringList = new ArrayList<>(Arrays.asList("apple", null, "banana", null, "orange")); 54 | // 55 | // stringList.removeAll(Collections.singleton(null)); 56 | // System.out.println("removed null "+stringList); 57 | // 58 | // 59 | // // Question 14: Sorting a List of Strings in Reverse Order 60 | // Collections.sort(fruitsList, Collections.reverseOrder()); 61 | // System.out.println("fruits list after sorting in reverse"+fruitsList); 62 | 63 | // Question 15: Finding the Index of the Last Occurrence of a sublist in a List 64 | 65 | int lastIndex = Collections.lastIndexOfSubList(fruitsList, Arrays.asList("cherry", "banana")); 66 | 67 | System.out.println("last index "+ lastIndex); 68 | 69 | // Question 16: Creating an Unmodifiable List 70 | List unmodif = Collections.unmodifiableList(Arrays.asList(7, 9, 2)); 71 | System.out.println(unmodif); 72 | 73 | 74 | // Question 17: Creating a Synchronized List 75 | 76 | List synchList = Collections.synchronizedList(fruitsList); 77 | synchList.add("dragonfruit"); 78 | System.out.println(synchList); 79 | } 80 | } 81 | 82 | 83 | -------------------------------------------------------------------------------- /ArraysDemo/Demo.java: -------------------------------------------------------------------------------- 1 | package org.codewithease.javatopics.ArraysANDCollections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | public class Demo { 10 | 11 | /* 12 | 13 | Implement a function to reverse the order of elements in an ArrayList using the Collections class. 14 | Write a program to find the frequency of elements in an ArrayList using the Collections class. 15 | Implement a function to check if two arrays are equal using the Arrays class. 16 | Create a method to shuffle the elements in an ArrayList using the Collections class. 17 | Write a program to convert an ArrayList to an array using the toArray() method. 18 | Implement a function to find the index of a specific element in an ArrayList using the Collections class. 19 | */ 20 | 21 | 22 | public static void main(String[] args) { 23 | 24 | //Write a program to find the maximum element in an array using the Arrays class. 25 | int[] array = {5, 8, 3, 2, 9, 1}; 26 | int max = Arrays.stream(array).max().orElse(0); 27 | System.out.println(max); 28 | 29 | 30 | //Implement a function to remove duplicates from an ArrayList using the Collections class. 31 | 32 | List list = Arrays.asList(3, 5, 3, 2, 1, 5); 33 | list.stream().distinct().collect(Collectors.toList()).forEach(System.out::println); 34 | 35 | 36 | System.out.println("sort descending"); 37 | //Create a method to sort an ArrayList in descending order using the Collections class. 38 | 39 | // list.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList()).forEach(System.out::println); 40 | Collections.sort(list, Collections.reverseOrder()); 41 | System.out.println("Sorted list in descending order: " + list); 42 | 43 | //Write a program to find the common elements between two arrays using the Arrays class. 44 | 45 | Integer[] array1 = {1, 2, 3, 4, 5}; 46 | Integer[] array2 = {4, 5, 6, 7, 8}; 47 | ArrayList commonElements = new ArrayList<>(Arrays.asList(array1)); 48 | commonElements.retainAll(Arrays.asList(array2)); 49 | System.out.println("Common elements: " + commonElements); 50 | 51 | 52 | } 53 | 54 | 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /ArraysDemo/Employee.java: -------------------------------------------------------------------------------- 1 | package org.codewithease.javatopics.commons; 2 | 3 | import java.util.Objects; 4 | 5 | public class Employee { 6 | private int age; 7 | private int id; 8 | private int salary; 9 | private String name; 10 | 11 | public Employee(int id, String name, int age, int salary) { 12 | this.age = age; 13 | this.id = id; 14 | this.salary = salary; 15 | this.name = name; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "Employee{" + 21 | "age=" + age + 22 | ", id=" + id + 23 | ", salary=" + salary + 24 | ", name='" + name + '\'' + 25 | '}'; 26 | } 27 | 28 | public int getSalary() { 29 | return salary; 30 | } 31 | 32 | // @Override 33 | // public boolean equals(Object o) { 34 | // if (this == o) return true; 35 | // if (o == null || getClass() != o.getClass()) return false; 36 | // Employee employee = (Employee) o; 37 | // return id == employee.id; 38 | // } 39 | // 40 | // @Override 41 | // public int hashCode() { 42 | // return Objects.hash(id); 43 | // } 44 | 45 | public void setSalary(int salary) { 46 | this.salary = salary; 47 | } 48 | 49 | public int getAge() { 50 | return age; 51 | } 52 | 53 | 54 | public void setAge(int age) { 55 | this.age = age; 56 | } 57 | 58 | public String getName() { 59 | return name; 60 | } 61 | 62 | public void setName(String name) { 63 | this.name = name; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Cloning/DeepShallowDemo.java: -------------------------------------------------------------------------------- 1 | package org.codewithease.javatopics.Cloning; 2 | 3 | class Person implements Cloneable { 4 | String name; 5 | Address address; // Non-primitive field 6 | 7 | public Person(String name, Address address) { 8 | this.name = name; 9 | this.address = address; 10 | } 11 | 12 | public void setName(String name) { 13 | this.name = name; 14 | } 15 | 16 | public Address getAddress() { 17 | return address; 18 | } 19 | 20 | public void setAddress(Address address) { 21 | this.address = address; 22 | } 23 | 24 | @Override 25 | protected Object clone() throws CloneNotSupportedException { 26 | return super.clone(); 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return "Person [name=" + name + ", address=" + address + "]"; 32 | } 33 | 34 | 35 | 36 | } 37 | class Address { 38 | String city; 39 | 40 | public Address(String city) { 41 | this.city = city; 42 | } 43 | 44 | public void setCity(String city) { 45 | this.city = city; 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "Address [city=" + city + "]"; 51 | } 52 | } 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Cloning/Main.java: -------------------------------------------------------------------------------- 1 | package org.codewithease.javatopics.Cloning; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws CloneNotSupportedException { 5 | Address address = new Address("kolkata"); 6 | Person person1 = new Person("Varsha",address ); 7 | Person person2 = (Person) person1.clone(); 8 | 9 | person2.address.setCity("mumbai"); 10 | System.out.println(person1); 11 | System.out.println(person2); 12 | 13 | 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Java8/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | Java8 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | org.apache.maven.plugins 14 | maven-compiler-plugin 15 | 16 | 11 17 | 11 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Java8/src/main/java/ComparatorDemo.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import org.codewithease.javatopics.commons.Employee; 4 | 5 | import java.time.LocalDate; 6 | import java.util.Arrays; 7 | import java.util.Collections; 8 | import java.util.Comparator; 9 | import java.util.List; 10 | 11 | public class ComparatorDemo { 12 | 13 | public static void main(String[] args) { 14 | 15 | /* 16 | Sort List of Objects 17 | 18 | Custom Sorting Criteria 19 | 20 | Multiple Sorting Criteria 21 | 22 | Case-Insensitive Sorting 23 | 24 | Reverse Order Sorting 25 | */ 26 | 27 | //1. Sort the strings based on their length in ascending order 28 | List fruits = Arrays.asList("apple", "cherry", "banana", "pineapple", "kiwi", "elderberry"); 29 | 30 | // fruits.sort(Comparator.comparingInt(String::length)); 31 | Collections.sort(fruits, Comparator.comparingInt(String::length)); 32 | 33 | System.out.println("fruits "+fruits); 34 | 35 | 36 | // 2.Sort the list of integers in descending order and print the result 37 | 38 | List nums = Arrays.asList(3,2,90,34,21,12); 39 | nums.sort(Comparator.reverseOrder()); 40 | 41 | System.out.println("nums in reverse order : "+nums); 42 | 43 | 44 | // 3.Sort the list of employees based on their age in ascending order and print the result 45 | 46 | List employees = Arrays.asList(new Employee(1, "Varsha", 28, 3000), 47 | new Employee(2, "Harsha", 21, 4000), 48 | new Employee(3, "Tony", 21, 1000), 49 | new Employee(4, "Ramesh", 30, 5000)); 50 | 51 | employees.sort(Comparator.comparingInt(Employee::getAge)); 52 | System.out.println("employees based on age "+employees); 53 | 54 | 55 | 56 | // 4.Sort the list of employees based on their age in ascending order. If the ages are the same, compare by salary. Print the result. 57 | 58 | employees.sort(Comparator.comparingInt(Employee::getAge).thenComparing(Employee::getSalary)); 59 | System.out.println( 60 | "employees with multiple sort criteria "+employees 61 | ); 62 | 63 | 64 | 65 | // 5.Sort the list of strings based on the index of the first occurrence of "e" in each string and print the result 66 | 67 | fruits.sort(Comparator.comparingInt(e -> e.indexOf("e"))); 68 | 69 | System.out.println("fruits with index position sorting :: "+ fruits); 70 | 71 | 72 | 73 | //6. Sort a list of strings ignoring case sensitivity using a case-insensitive comparator. 74 | 75 | List fruitsMix = Arrays.asList("APPLE", "cherry", "baNaNa", "pineapple", "KiWI", "elderberry"); 76 | Comparator caseInsensitiveComp = String.CASE_INSENSITIVE_ORDER; 77 | fruitsMix.sort(caseInsensitiveComp); 78 | 79 | System.out.println(fruitsMix); 80 | 81 | 82 | //7. Sort a list of dates in ascending order using the comparing() method with a lambda expression. 83 | List dates = Arrays.asList( 84 | LocalDate.of(2023, 5, 10), 85 | LocalDate.of(2023, 3, 15), 86 | LocalDate.of(2023, 7, 1) 87 | ); 88 | 89 | dates.sort(Comparator.comparing(date -> date)); 90 | 91 | System.out.println(dates); 92 | 93 | 94 | 95 | 96 | 97 | 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Java8/src/main/java/DateTime.md: -------------------------------------------------------------------------------- 1 | 2 | --- 3 | 4 | # Java 8 Date-Time API: `LocalDate`, `LocalTime`, and `LocalDateTime` 5 | 6 | ## Overview 7 | Java 8 introduced a new Date-Time API in the `java.time` package, which is thread-safe, immutable, and more comprehensive than the old `java.util.Date` and `java.util.Calendar`. The new API is divided into several classes for handling dates, times, and timestamps. Some of the most commonly used classes are: 8 | 9 | - `LocalDate`: Represents a date (year, month, day) without a time zone. 10 | - `LocalTime`: Represents a time (hours, minutes, seconds, nanoseconds) without a date or time zone. 11 | - `LocalDateTime`: Combines date and time without a time zone. 12 | 13 | --- 14 | 15 | ## Key Classes 16 | 17 | ### 1. **`LocalDate`** 18 | - Represents only a date (e.g., `2024-09-16`). 19 | - Used to store dates like birthdays, event dates, etc. 20 | - Methods: 21 | - `now()`: Gets the current date. 22 | - `of(int year, int month, int day)`: Creates a specific date. 23 | - `plusDays(), minusWeeks(), plusMonths()`: Manipulates dates. 24 | - `isLeapYear()`: Checks if the current year is a leap year. 25 | 26 | ### 2. **`LocalTime`** 27 | - Represents only a time (e.g., `12:30:15`). 28 | - Used for working with times like clock settings, schedules, etc. 29 | - Methods: 30 | - `now()`: Gets the current time. 31 | - `of(int hour, int minute, int second)`: Creates a specific time. 32 | - `plusHours(), minusMinutes()`: Manipulates time. 33 | - `isBefore(), isAfter()`: Compares times. 34 | 35 | ### 3. **`LocalDateTime`** 36 | - Combines `LocalDate` and `LocalTime` to represent both date and time (e.g., `2024-09-16T12:30:15`). 37 | - Methods: 38 | - `now()`: Gets the current date and time. 39 | - `of(LocalDate, LocalTime)`: Combines date and time. 40 | - `toLocalDate()`, `toLocalTime()`: Extracts date and time from `LocalDateTime`. 41 | - `format(DateTimeFormatter)`: Formats the date and time into a string. 42 | 43 | --- 44 | 45 | ## Formatting and Parsing Dates 46 | 47 | ### **`DateTimeFormatter`** 48 | To convert dates and times into a specific string format and vice versa, Java 8 introduced `DateTimeFormatter`. You can define patterns to format and parse date-time objects. 49 | 50 | Example: 51 | ```java 52 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); 53 | LocalDateTime dateTime = LocalDateTime.now(); 54 | String formattedDate = dateTime.format(formatter); // Formats date-time 55 | LocalDateTime parsedDateTime = LocalDateTime.parse("16-09-2024 12:30:00", formatter); // Parses date-time 56 | ``` 57 | 58 | --- 59 | 60 | ## Comparing Dates and Times 61 | 62 | You can compare dates and times using methods like `isBefore()`, `isAfter()`, and `isEqual()`: 63 | 64 | ```java 65 | LocalDate date1 = LocalDate.of(2024, 9, 16); 66 | LocalDate date2 = LocalDate.of(2024, 10, 1); 67 | 68 | boolean isBefore = date1.isBefore(date2); // true 69 | ``` 70 | 71 | --- 72 | 73 | ## Period and Duration 74 | 75 | ### **`Period`** 76 | - Used to represent a difference in terms of years, months, and days between two dates. 77 | 78 | ### **`Duration`** 79 | - Used to represent a difference between two times (in hours, minutes, seconds). 80 | 81 | Example: 82 | ```java 83 | LocalDate startDate = LocalDate.of(2023, 1, 1); 84 | LocalDate endDate = LocalDate.now(); 85 | Period period = Period.between(startDate, endDate); 86 | ``` 87 | 88 | --- 89 | 90 | ## Time Zones with `ZonedDateTime` 91 | 92 | Java 8 also introduces `ZonedDateTime` for working with time zones. You can convert a `LocalDateTime` to a specific time zone using `ZoneId`. 93 | 94 | Example: 95 | ```java 96 | LocalDateTime localDateTime = LocalDateTime.now(); 97 | ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Kolkata")); 98 | ``` 99 | 100 | --- 101 | 102 | ## Conclusion 103 | The Java 8 Date-Time API provides a much cleaner and more intuitive way of handling dates, times, and time zones compared to the older `java.util.Date`. It is designed to be immutable, thread-safe, and easy to use with its fluent API and well-defined methods. 104 | 105 | --- 106 | 107 | ## References 108 | - [Oracle Java Documentation](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) 109 | - [Baeldung - Java 8 Date-Time API](https://www.baeldung.com/java-8-date-time-intro) 110 | 111 | --- 112 | -------------------------------------------------------------------------------- /Java8/src/main/java/LinkedHashMapDemo.java: -------------------------------------------------------------------------------- 1 | package main.java; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | public class LinkedHashMapDemo { 6 | 7 | public static void main(String[] args) { 8 | // Create a LinkedHashMap with access order set to true 9 | Map linkedHashMap = new LinkedHashMap<>(16, 0.75f, true); 10 | //Map linkedHashMap = new LinkedHashMap<>(16, 0.75f, false); 11 | 12 | // Add elements to the LinkedHashMap 13 | linkedHashMap.put("One", 1); 14 | linkedHashMap.put("Two", 2); 15 | linkedHashMap.put("Three", 3); 16 | linkedHashMap.put("Four", 4); 17 | 18 | // Print the elements in insertion order 19 | System.out.println("LinkedHashMap elements in insertion order:"); 20 | printMap(linkedHashMap); 21 | 22 | // Access an element to change the access order 23 | System.out.println("\nAccessing an element to change access order: "+linkedHashMap.get("Two")); 24 | 25 | // Print the elements again to show access order 26 | System.out.println("\nLinkedHashMap elements after accessing an element (access order):"); 27 | printMap(linkedHashMap); 28 | } 29 | 30 | private static void printMap(Map map) { 31 | for (Map.Entry entry : map.entrySet()) { 32 | System.out.println(entry.getKey() + ": " + entry.getValue()); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Java8/src/main/java/Optionals/OptionalCodeDemo.java: -------------------------------------------------------------------------------- 1 | package main.java.Optionals; 2 | 3 | import java.util.Objects; 4 | import java.util.Optional; 5 | 6 | public class OptionalCodeDemo { 7 | public static void main(String[] args) { 8 | // Example 1: Creating an Optional with a non-null value 9 | Optional optional1 = Optional.of("varsha"); 10 | System.out.println(optional1.get()); 11 | 12 | 13 | // Example 2: Creating an empty Optional 14 | 15 | Optional optionalEmpty = Optional.empty(); 16 | System.out.println(optionalEmpty); 17 | 18 | 19 | 20 | // Example 3: Creating an Optional with a potentially null value 21 | 22 | 23 | Optional optionalWithNullValue = Optional.ofNullable(null); 24 | System.out.println("optionalWithNullValue :"+optionalWithNullValue); 25 | 26 | 27 | // Example 4: Checking if Optional contains a value 28 | 29 | if(optionalWithNullValue.isPresent()){ 30 | System.out.println("yes optional value exists "+optionalWithNullValue.get()); 31 | } else { 32 | System.out.println("optional does not exist"); 33 | } 34 | 35 | //api - Optional - explicitly handle it - 36 | 37 | 38 | 39 | // Example 5: Default value if Optional is empty 40 | 41 | String optWithDefault = optionalWithNullValue.orElse("Default value"); 42 | System.out.println(optWithDefault); 43 | 44 | 45 | // Example 6: Default value supplier if Optional is empty 46 | 47 | String optWithDefaultSupplier = optionalWithNullValue.orElseGet(() -> "Default value with supplier"); 48 | System.out.println(optWithDefaultSupplier); 49 | 50 | 51 | // Example 7: Throw exception if Optional is empty 52 | 53 | try { 54 | optionalWithNullValue.orElseThrow(); 55 | } catch (Exception e){ 56 | System.out.println("exception occured"+e); 57 | } 58 | 59 | 60 | // Example 8: Filter and map operations on Optional 61 | Optional optInt = Optional.of(50); 62 | Optional optFiltered = optInt.filter(val -> val < 10); 63 | Optional optString = optFiltered.map(Objects::toString); 64 | System.out.println(optString.orElse("default mapped value")); 65 | 66 | 67 | // Example 9: Chaining methods on Optional 68 | 69 | String chainedOutput = Optional.of("Hello") 70 | .map(s -> s.concat("World")) 71 | .filter(s -> s.length() > 15) 72 | .orElse("default string"); 73 | 74 | System.out.println(chainedOutput); 75 | 76 | 77 | // Example 10: Transforming Optional to Stream 78 | 79 | Optional.of("some string").stream().forEach(System.out::println); 80 | 81 | optional1.ifPresent(x -> System.out.println("hey optional is present")); 82 | 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Java8/src/main/java/Optionals/OptionalDemo.java: -------------------------------------------------------------------------------- 1 | package Optionals; 2 | 3 | import java.util.NoSuchElementException; 4 | import java.util.Optional; 5 | 6 | public class OptionalDemo { 7 | 8 | public static void main(String[] args) { 9 | // Example 1: Creating an Optional with a non-null value 10 | Optional optional1 = Optional.of("Hello"); 11 | System.out.println("1. Optional with non-null value: " + optional1); 12 | 13 | // Example 2: Creating an empty Optional 14 | Optional optional2 = Optional.empty(); 15 | System.out.println("2. Empty Optional: " + optional2); 16 | 17 | // Example 3: Creating an Optional with a potentially null value 18 | String str = "World"; 19 | Optional optional3 = Optional.ofNullable(null); 20 | System.out.println("3. Optional with potentially null value: " + optional3); 21 | 22 | // Example 4: Checking if Optional contains a value 23 | if (optional3.isPresent()) { 24 | System.out.println("4. Optional contains a value: " + optional3.get()); 25 | } else { 26 | System.out.println("4. Optional is empty"); 27 | } 28 | 29 | // Example 5: Default value if Optional is empty 30 | String value = optional2.orElse("Default Value"); 31 | System.out.println("5. Value of Optional (or default): " + value); 32 | 33 | // Example 6: Default value supplier if Optional is empty 34 | String valueSupplier = optional2.orElseGet(() -> "Default Value from Supplier"); 35 | System.out.println("6. Value of Optional (or default from supplier): " + valueSupplier); 36 | 37 | // Example 7: Throw exception if Optional is empty 38 | try { 39 | String valueOrThrow = optional2.orElseThrow(() -> new NoSuchElementException("Optional is empty")); 40 | System.out.println("7. Value of Optional (or throw exception): " + valueOrThrow); 41 | } catch (NoSuchElementException e) { 42 | System.out.println("7. " + e.getMessage()); 43 | } 44 | 45 | // Example 8: Filter and map operations on Optional 46 | Optional optionalInt = Optional.of(10); 47 | Optional filtered = optionalInt.filter(x -> x > 5); 48 | Optional mapped = filtered.map(Object::toString); 49 | System.out.println("8. Filtered and mapped value: " + mapped.orElse("Empty")); 50 | 51 | // Example 9: Chaining methods on Optional 52 | String result = Optional.of("Hello") 53 | .map(s -> s + " World") 54 | .filter(s -> s.length() > 5) 55 | .orElse("Too short"); 56 | System.out.println("9. Chained methods result: " + result); 57 | 58 | // Example 10: Transforming Optional to Stream 59 | Optional optionalString = Optional.of("Transform"); 60 | optionalString.stream().forEach(System.out::println); 61 | 62 | Optional optional = Optional.of("hello"); 63 | optional.ifPresent(val -> System.out.println("Value: " + value)); 64 | } 65 | } 66 | 67 | 68 | -------------------------------------------------------------------------------- /Java8/src/main/java/Optionals/OptionalREADME.md: -------------------------------------------------------------------------------- 1 | **README.md** 2 | 3 | # Optional in Java 4 | 5 | ## What is Optional? 6 | 7 | `Optional` is a container object that may or may not contain a non-null value. It was introduced in Java 8 as part of the `java.util` package to represent optional values and to deal with the problem of null references in a more effective and expressive way. 8 | 9 | ## Why Optional? 10 | 11 | Prior to the introduction of `Optional` in Java 8, handling null values often led to NullPointerExceptions (NPEs), which could be difficult to debug and manage. `Optional` provides a more explicit and safer way to handle the absence of a value, reducing the likelihood of NPEs and improving code clarity and robustness. 12 | 13 | ## Before Optional 14 | 15 | Before the introduction of `Optional`, developers commonly used null references to represent the absence of a value. This approach often resulted in code that was hard to read, maintain, and debug. Null checks were required everywhere, leading to verbose and error-prone code. Additionally, it was not always clear whether a method could return null or not, making it challenging to reason about the behavior of the code. 16 | 17 | ## Problems Solved by Optional 18 | 19 | ### 1. Null Pointer Safety 20 | - `Optional` provides a safer alternative to null references, reducing the risk of NullPointerExceptions and improving code reliability. 21 | 22 | ### 2. Improved Code Readability 23 | - By using `Optional`, code becomes more expressive and self-documenting, as it clearly indicates whether a value may be absent or present. 24 | 25 | ### 3. Forced Null Checking 26 | - `Optional` encourages developers to explicitly handle the case of a missing value, either by providing a default value or performing an alternative action, thus promoting defensive programming practices. 27 | 28 | ## Basic Methods 29 | 30 | ### Creation: 31 | - `Optional.of(T value)`: Creates an `Optional` with the specified non-null value, throwing a NullPointerException if the value is null. 32 | - `Optional.ofNullable(T value)`: Creates an `Optional` with the specified value, which may be null. 33 | 34 | ### Checking for Presence: 35 | - `isPresent()`: Returns true if the `Optional` contains a non-null value. 36 | - `isEmpty()`: Returns true if the `Optional` is empty. 37 | 38 | ### Getting the Value: 39 | - `get()`: Returns the value if present, otherwise throws a NoSuchElementException. 40 | 41 | ### Conditional Retrieval: 42 | - `orElse(T other)`: Returns the value if present, otherwise returns the specified default value. 43 | - `orElseGet(Supplier other)`: Returns the value if present, otherwise invokes the specified supplier and returns its result. 44 | - `orElseThrow()`: Returns the value if present, otherwise throws the specified exception. 45 | 46 | ### Mapping and Filtering: 47 | - `map(Function mapper)`: Applies the specified mapping function to the value if present. 48 | - `flatMap(Function> mapper)`: Applies the specified mapping function to the value if present and returns the result. 49 | - `filter(Predicate predicate)`: If a value is present, applies the given predicate to it, and returns an `Optional` describing the value if the predicate returns true. 50 | 51 | ### Utility Methods: 52 | - `ifPresent(Consumer consumer)`: If a value is present, performs the given action with the value. 53 | - `ifPresentOrElse(Consumer action, Runnable emptyAction)`: If a value is present, performs the given action with the value, otherwise performs the specified empty action. 54 | - `equals(Object obj)`: Indicates whether some other object is "equal to" this Optional. 55 | 56 | ## Conclusion 57 | 58 | `Optional` provides a more structured and reliable approach to handling optional values in Java, addressing common pitfalls associated with null references. By encouraging explicit handling of absent values and providing a rich set of methods for working with optionals, `Optional` improves code clarity, safety, and maintainability. -------------------------------------------------------------------------------- /Java8/src/main/java/Person.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Objects; 3 | 4 | public class Person { 5 | private String name; 6 | private int age; 7 | 8 | public void setName(String name) { 9 | this.name = name; 10 | } 11 | 12 | 13 | 14 | public int getAge() { 15 | return age; 16 | } 17 | 18 | public void setAge(int age) { 19 | this.age = age; 20 | } 21 | 22 | public Person(String name,int age) { 23 | this.name = name; 24 | this.age = age; 25 | 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return "Person{" + 31 | "name='" + name + '\'' + 32 | ", age=" + age + 33 | '}'; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | @Override 41 | public boolean equals(Object o) { 42 | if (this == o) return true; 43 | if (o == null || getClass() != o.getClass()) return false; 44 | Person person = (Person) o; 45 | return name.equals(person.name) && age == person.age; 46 | } 47 | 48 | @Override 49 | public int hashCode() { 50 | return Objects.hash(name, age); 51 | } 52 | 53 | 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /Java8/src/main/java/README-Comparators.md: -------------------------------------------------------------------------------- 1 | # Java Comparators - In-Depth Overview 2 | 3 | ## Introduction 4 | 5 | In Java, the `Comparator` interface is used to define custom ordering for objects. 6 | 7 | Using the `Comparator` interface, we can efficiently sort collections, arrays, and other data structures in a desired order. 8 | 9 | ## 1. When to Use Comparator Interface 10 | 11 | The `Comparator` interface in Java provides a flexible way to define custom comparison logic for objects. It is used when: 12 | 13 | - The class of the objects being compared does not implement the `Comparable` interface. 14 | - The natural ordering defined by the `Comparable` interface is not suitable. 15 | - Custom sorting criteria need to be defined for specific use cases. 16 | 17 | ## 2. Difference with Comparable Interface 18 | 19 | The `Comparable` interface is another way to provide ordering for objects in Java. 20 | Unlike the `Comparator` interface, the `Comparable` interface is implemented by the class of the objects being compared. 21 | It defines the natural ordering of objects within the class itself. In contrast, the `Comparator` interface allows for external comparison 22 | logic to be defined independently of the objects being compared. This distinction is important when we want to sort objects based on 23 | different criteria without modifying their original class. 24 | 25 | ## Basic Usage 26 | 27 | - Implementing the `Comparator` interface requires defining the `compare()` method, which takes two objects and returns an integer. 28 | - The `compare()` method should follow the contract: 29 | - Return a negative value if the first object is less than the second. 30 | - Return zero if the objects are considered equal. 31 | - Return a positive value if the first object is greater than the second. 32 | 33 | ## Creating Comparators 34 | 35 | - Comparators can be created in several ways: 36 | - Implementing the `Comparator` interface directly. 37 | - Using lambda expressions or method references. 38 | - Utilizing the `Comparator` utility methods like `comparing()`, `reversed()`, or `thenComparing()`. 39 | 40 | ```import 41 | 42 | // Implementing the Comparator interface directly 43 | class AgeComparator implements Comparator { 44 | @Override 45 | public int compare(Person p1, Person p2) { 46 | return Integer.compare(p1.getAge(), p2.getAge()); 47 | } 48 | } 49 | 50 | // Using lambda expressions or method references 51 | Comparator nameComparator = (p1, p2) -> p1.getName().compareTo(p2.getName()); 52 | 53 | // Utilizing the Comparator utility methods 54 | Comparator salaryComparator = Comparator.comparingDouble(Person::getSalary); 55 | Comparator reversedNameComparator = Comparator.comparing(Person::getName).reversed(); 56 | Comparator combinedComparator = Comparator.comparing(Person::getDepartment) 57 | .thenComparing(Person::getAge); 58 | 59 | 60 | ``` 61 | 62 | ## Real world usecases: 63 | 64 | 1. Sorting a List of Objects: Comparators are commonly used to sort collections of objects based on specific attributes. For example, in an e-commerce application, you may need to sort a list of products by price or popularity using custom comparators. 65 | 2. Implementing Custom Sorting Logic: When the natural ordering of objects is not appropriate or needs to be overridden, comparators come in handy. For instance, in a task management system, you might want to sort tasks based on priority, deadline, or a combination of multiple factors. 66 | 3. Filtering and Searching: Comparators can be used to filter and search for specific elements in a collection. For instance, in a contact management application, you can use a comparator to search for contacts based on their names or other attributes. 67 | 68 | ## Sorting Collections 69 | 70 | - To sort a collection using a custom comparator, the `Collections.sort()` method is commonly used. 71 | - The `sort()` method allows passing a comparator as the second argument to define the sorting order. 72 | - Sorting can be done in ascending or descending order by choosing appropriate comparators or utilizing the `reversed()` method. 73 | 74 | ## Chaining Comparators 75 | 76 | - Multiple criteria for sorting can be achieved by chaining comparators using the `thenComparing()` method. 77 | - `thenComparing()` enables secondary sorting based on another criterion if the primary criterion is the same. 78 | 79 | ## Predefined Comparators 80 | 81 | - Java provides predefined comparators in the `Comparator` interface as utility methods. 82 | - Some commonly used ones include `naturalOrder()`, `reverseOrder()`, and methods for comparing primitives like `comparingInt()`, `comparingDouble()`, etc. 83 | 84 | ## Custom Objects 85 | 86 | - When comparing custom objects, you need to implement the `Comparable` interface or provide a separate `Comparator` implementation. 87 | - Implementing `Comparable` enables natural ordering, while a separate `Comparator` provides custom ordering without modifying the original class. 88 | 89 | ## Null Handling 90 | 91 | - Comparators can handle null values through methods like `nullsFirst()` or `nullsLast()`. 92 | - These methods allow specifying the position of null values in the sorted result. 93 | 94 | ## Summary 95 | 96 | Java comparators provide a flexible way to customize sorting and ordering of objects. By implementing the `Comparator` interface or utilizing utility methods, you can define complex sorting logic. Understanding comparators is crucial for sorting collections and creating custom ordering for objects in Java applications. 97 | -------------------------------------------------------------------------------- /Java8/src/main/java/README-Streams.md: -------------------------------------------------------------------------------- 1 | # 2 | 3 | # Java Streams 4 | 5 | A *Stream in Java* - **sequence of elements from a source**. 6 | 7 | ## Background and History 8 | 9 | Before Java 8, working with collections in Java involved writing iterative loops and manually performing operations on the data. However, Java 8 introduced Java Streams, a game-changing feature that brought functional programming concepts to the Java language. This opened up new possibilities for writing expressive and concise code when working with collections. 10 | 11 | 12 | ## Importance of Learning Java Streams 13 | 14 | Learning Java Streams is crucial for several reasons. Firstly, it enables you to write more readable and maintainable code. With the power of lambda expressions and functional interfaces, you can perform complex operations on collections in a more concise and expressive manner. 15 | 16 | Secondly, Java Streams promote a declarative style of programming, where you focus on describing what you want to achieve rather than the step-by-step implementation details. This leads to cleaner code that is easier to understand and maintain. 17 | 18 | Furthermore, Java Streams provide a higher level of abstraction, allowing you to perform common data manipulation tasks such as filtering, mapping, and reducing with simplicity and efficiency. This abstraction makes your code more modular and reusable, saving you time and effort in the long run. 19 | 20 | ## Operations 21 | 22 | #### Stream Creation 23 | 24 | Streams can be created from various data sources such as collections, arrays, I/O channels, or generator functions. Here are examples of creating stream 25 | 26 | ``` 27 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 28 | Stream streamFromList = numbers.stream(); 29 | 30 | int[] array = {1, 2, 3, 4, 5}; 31 | IntStream streamFromArray = Arrays.stream(array); 32 | 33 | Stream streamFromIO = Files.lines(Paths.get("file.txt")); 34 | 35 | Stream streamFromGenerator = Stream.generate(() -> 42); 36 | 37 | ``` 38 | 39 | #### Intermediate Operations 40 | 41 | Intermediate operations are used to transform, filter, or manipulate the elements of a Stream. They return a new Stream as a result. Some commonly used intermediate operations are: 42 | 43 | * `filter(Predicate)`: Filters elements based on a given condition. 44 | * `map(Function)`: Transforms each element of the Stream to another type. 45 | * `flatMap(Function> )`: Flattens nested Streams into a single Stream. 46 | 47 | #### Terminal Operations 48 | 49 | Terminal operations produce a final result or a side effect. They trigger the processing of the Stream and do not return another Stream. Examples of terminal operations are: 50 | 51 | * `forEach(Consumer)`: Performs an action for each element in the Stream. 52 | * `collect(Collector)`: Accumulates the elements into a collection or other data structure. 53 | * `reduce(BinaryOperator)`: Performs a reduction on the elements of the Stream. 54 | 55 | #### Lazy Evaluation 56 | 57 | Java Streams employ lazy evaluation, which means that the elements of a Stream are processed on-demand, only when a terminal operation is invoked. This approach allows for optimization by avoiding unnecessary computations and improving performance when working with large or infinite Streams. 58 | -------------------------------------------------------------------------------- /Java8/src/main/java/StreamsAllCodeSolutions.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.stream.Collectors; 3 | 4 | public class StreamsAllCodeSolutions { 5 | public static void main(String[] args) { 6 | List nums = Arrays.asList(1,2,3,4,5,6,8,101); 7 | int[] arr = {1,2,3,4}; 8 | // Write a program to find the sum of all elements in a List using streams. 9 | int sums = nums.stream().mapToInt(Integer::intValue).sum(); 10 | System.out.println(sums); 11 | 12 | 13 | //Given a List of integers, write a program to find the maximum element using streams. 14 | int max = nums.stream().max(Comparator.naturalOrder()).get(); 15 | 16 | System.out.println("max element :"+max); 17 | 18 | List fruits = Arrays.asList("apple", "banana", "cherry", "coconut", "apple"); 19 | 20 | //Given a List of strings, write a program to count the number of strings that start with a specific character using streams. 21 | long fruitCount = fruits.stream().filter( s -> s.startsWith("c")).count(); 22 | System.out.println("fruitCount: "+fruitCount); 23 | 24 | 25 | //Write a program to convert a List of strings to uppercase using streams. 26 | fruits.stream().map(String::toUpperCase).forEach(System.out::println); 27 | 28 | //Given a List of integers, write a program to filter out the even numbers using streams. 29 | // Count the number of elements in a list that satisfy a specific condition using streams. 30 | 31 | nums.stream().filter(n -> n % 2 == 0).forEach(System.out::println); 32 | int even = (int) nums.stream().filter(n -> n % 2 == 0).count(); 33 | System.out.println("no of even "+even); 34 | 35 | 36 | //Write a program to find the average of a List of floating-point numbers using streams. 37 | List numsFloat = Arrays.asList(1.3, 2.4, 3.1, 4.2, 5.4); 38 | double avg = numsFloat.stream().mapToDouble(Double::doubleValue).average().getAsDouble(); 39 | System.out.println("avg ::"+avg); 40 | 41 | //Given a List of strings, write a program to concatenate all the strings using streams. 42 | String concat = fruits.stream().collect(Collectors.joining()); 43 | System.out.println(concat); 44 | 45 | //Write a program to remove duplicate elements from a List using streams. 46 | fruits.stream().distinct().forEach(System.out::println); 47 | 48 | //Given a List of objects, write a program to sort the objects based on a specific attribute using streams. 49 | List people = Arrays.asList( 50 | new Person("Alice", 21), 51 | new Person("Anna", 29), 52 | new Person("Bob", 30), 53 | new Person("Barbie", 56), 54 | new Person("Charlie", 20) 55 | ); 56 | 57 | people.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList()).forEach(System.out::println); 58 | 59 | //Write a program to check if all elements in a List satisfy a given condition using streams. 60 | List numbers = Arrays.asList(2, 4, 6, 8, 10); 61 | boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0); 62 | System.out.println("All numbers are even: " + allEven); 63 | 64 | 65 | //Sort a list of strings in ascending order using streams. 66 | fruits.stream().sorted().collect(Collectors.toList()).forEach(System.out::println); 67 | 68 | //Check if a list contains a specific element using streams. 69 | boolean exists = nums.stream().anyMatch(n -> n.equals(9)); 70 | System.out.println(exists); 71 | 72 | //Create a new list containing the square of each element from the original list using streams 73 | nums.stream().map(n -> n*n).collect(Collectors.toList()).forEach(System.out::println); 74 | 75 | //Find the average length of strings in a list using streams. 76 | fruits.stream().mapToInt(String::length).average(); 77 | 78 | //Find the longest string in a list using streams. 79 | fruits.stream().mapToInt(String::length).max(); 80 | 81 | // Group a list of objects based on a specific attribute using streams. 82 | // List sortedEmployees = people.stream() 83 | // .sorted(Comparator.comparing(Employee::getDepartment) 84 | // .thenComparing(Employee::getSalary)) 85 | // .collect(Collectors.toList()); 86 | 87 | 88 | //Remove null values from a list using streams. 89 | List nonNullValues = fruits.stream() 90 | .filter(Objects::nonNull) 91 | .collect(Collectors.toList()); 92 | 93 | 94 | //Find the second smallest element in a list of integers using streams. 95 | Optional secondSmallest = numbers.stream() 96 | .distinct() 97 | .sorted() 98 | .skip(1) 99 | .findFirst(); 100 | 101 | 102 | 103 | //Find the intersection of two lists using streams 104 | List list1 = Arrays.asList(1, 2, 3, 4, 5); 105 | List list2 = Arrays.asList(4, 5, 6, 7, 8); 106 | 107 | List intersection = list1.stream() 108 | .filter(list2::contains) 109 | .collect(Collectors.toList()); 110 | 111 | 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Java8/src/main/java/StreamsCodeDemoPart2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.function.Function; 3 | import java.util.stream.Collectors; 4 | import java.util.stream.IntStream; 5 | import java.util.stream.Stream; 6 | 7 | public class StreamsCodeDemoPart2 { 8 | public static void main(String[] args) { 9 | 10 | //1. Given a sentence, find and print the frequency of each word. 11 | String sentence = "Java is a programming language. Java is versatile."; 12 | 13 | Map wordFreqMap = Arrays.stream(sentence.split("\\s+")) 14 | .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); 15 | 16 | 17 | // System.out.println(wordFreqMap); 18 | 19 | //2. Given a list of integers, find out all the numbers starting with 1. 20 | 21 | List nums = Arrays.asList(12, 13, 18, 21, 90, 11); 22 | 23 | List numsWithOne = nums.stream().filter( n -> String.valueOf(n).startsWith("1")).collect(Collectors.toList()); 24 | 25 | // System.out.println(numsWithOne); 26 | 27 | //3. Given a list of names, group them by their first letter, and then count the number of names in each group. 28 | 29 | String[] names = {"Alice", "Bob", "Charlie", "Amy", "Bill", "Anna"}; 30 | 31 | Map namesMap = Arrays.stream(names).collect(Collectors.groupingBy(s -> s.charAt(0), Collectors.counting())); 32 | 33 | // System.out.println(namesMap); 34 | 35 | 36 | // 4. Find and print duplicate numbers in an array if it contains multiple duplicates? 37 | 38 | int[] arr = {2,4,2,3,1,5, 5,78,3,1,5}; 39 | 40 | // Arrays.stream(arr).boxed() 41 | // .collect(Collectors.groupingBy(e-> e, Collectors.counting())) 42 | // .entrySet().stream() 43 | // //key -value - 2 (k), 2(val) 44 | // .filter(entry -> entry.getValue() > 1) 45 | // .map(Map.Entry::getKey) 46 | // .forEach(System.out::println); 47 | 48 | 49 | // 5. How are duplicates removed from a given array in Java? 50 | // 51 | int[] arr2 = {2,4,2,3,1,78}; 52 | 53 | int[] newarr = Arrays.stream(arr).distinct().toArray(); 54 | 55 | // System.out.println(Arrays.toString(newarr)); 56 | 57 | 58 | //6. Given a list of words, filter and print the palindromes 59 | 60 | List strings = List.of("level", "hello", "radar", "world", "deed"); 61 | 62 | List palindromeWords = strings.stream(). 63 | filter(str -> str.equals(new StringBuilder(str).reverse().toString())).collect(Collectors.toList()); 64 | 65 | // System.out.println(palindromeWords); 66 | 67 | 68 | // 7. How do you merge two sorted arrays into a single sorted array? 69 | int[] array1 = {1, 3,32, 5, 7}; 70 | int[] array2 = {2, 4, 6,62, 8}; 71 | 72 | int[] sortedArray = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).sorted().toArray(); 73 | // System.out.println(Arrays.toString(sortedArray)); 74 | 75 | 76 | //8. Given two lists of strings, concatenate them and remove duplicates. 77 | 78 | List list1 = List.of("apple", "banana", "orange"); 79 | List list2 = List.of("banana", "kiwi", "grape"); 80 | 81 | List uniqueList = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toList()); 82 | // System.out.println(uniqueList); 83 | 84 | 85 | // 9. Student Grade Classification - 70 and above pass 86 | 87 | List students = List.of( 88 | new Student("Alice", 85), 89 | new Student("Bob", 60), 90 | new Student("Charlie", 75), 91 | new Student("David", 90) 92 | ); 93 | 94 | 95 | Map> studentMap = 96 | students.stream().collect(Collectors.groupingBy(student -> student.grade >= 70 ? "Pass" : "Fail")); 97 | 98 | // System.out.println(studentMap); 99 | 100 | 101 | //10. Given a list of strings, sort them according to increasing order of their length. 102 | 103 | List fruits = Arrays.asList("Mango","pear" ,"Apple", "Banana", "Pineapple", "Kiwi"); 104 | 105 | fruits.stream().sorted(Comparator.comparingInt(String::length)).forEach(System.out::println); 106 | 107 | 108 | //12.Partition a list of numbers into two groups: even and odd, using a custom predicate. 109 | List numbers1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 110 | Map> partitionedNumbers = numbers1.stream() 111 | .collect(Collectors.partitioningBy(n -> n % 2 == 0)); 112 | 113 | System.out.println(partitionedNumbers); 114 | 115 | //13. Find the squares of the first three even numbers in a list. 116 | 117 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 118 | List firstThreeSquares = numbers.stream() 119 | .filter(n -> n % 2 == 0) 120 | .map(n -> n * n) 121 | .limit(3) 122 | .collect(Collectors.toList()); 123 | 124 | // 14. Flatten a list of lists 125 | 126 | List> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6)); 127 | List flattenedList = listOfLists.stream() 128 | .flatMap(List::stream) 129 | .collect(Collectors.toList()); 130 | 131 | System.out.println(flattenedList); 132 | 133 | 134 | 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /Java8/src/main/java/StreamsPart2.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.stream.*; 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.function.Function; 7 | import java.util.stream.Collectors; 8 | import java.util.stream.IntStream; 9 | import java.util.stream.Stream; 10 | 11 | public class StreamsPart2 { 12 | 13 | public static void main(String[] args) { 14 | 15 | List numbers = Arrays.asList(123, 45, 167, 189, 12, 1234, 198, 102); 16 | 17 | List fruits = Arrays.asList("Mango", "Apple", "Banana", "Kiwi"); 18 | 19 | //1. Given a list of integers, find the total number of elements present in the list. 20 | String str = "madam"; 21 | 22 | //1. Given a list of integers, find the total number of elements present in the list. 23 | 24 | long totalCount = numbers.stream().count(); 25 | System.out.println("Total number of elements: " + totalCount); 26 | 27 | //2. Given a list of integers, find out all the numbers starting with 1. 28 | 29 | List numbersStartingWithOne = numbers.stream().filter(number -> String.valueOf(number).startsWith("1")).collect(Collectors.toList()); 30 | System.out.println("Numbers starting with 1: " + numbersStartingWithOne); 31 | 32 | //3. Find the frequency of each element in an array. 33 | 34 | Integer[] array = {1, 2, 3, 2, 4, 1, 5, 2, 3, 1, 4, 4, 5}; 35 | Map frequencyMap = Arrays.stream(array).collect(Collectors.groupingBy(e -> e, Collectors.counting())); 36 | System.out.println("Frequency of each element: " + frequencyMap); 37 | 38 | //4. Count the total number of vowels in a collection of strings. 39 | 40 | long totalVowels = fruits.stream() 41 | .flatMapToInt(CharSequence::chars) // Flatten strings to a stream of characters 42 | .filter(c -> "aeiouAEIOU".indexOf(c) != -1) // Filter out vowels 43 | .count(); 44 | System.out.println("Total number of vowels: " + totalVowels); 45 | 46 | //5. Count the occurrences of each character in a given string and return a map with character frequencies. 47 | 48 | Map charFrequencyMap = str.chars().mapToObj(c -> (char) c) 49 | .collect(Collectors.groupingBy(c -> c, Collectors.counting())); 50 | System.out.println("Character frequencies: " + charFrequencyMap); 51 | 52 | //6. Given a list of integers, sort all the values present in it in descending order. 53 | 54 | List sortedDescending = numbers.stream() 55 | .sorted(Comparator.reverseOrder()) // Comparator.reverseOrder() 56 | .collect(Collectors.toList()); 57 | System.out.println("Sorted in descending order: " + sortedDescending); 58 | 59 | //7. Given a list of strings, sort them according to increasing order of their length. 60 | 61 | List sortedByLength = fruits.stream().sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList()); 62 | System.out.println("Sorted by length in increasing order: " + sortedByLength); 63 | 64 | //8. Given two lists of strings, merge them and remove duplicates. 65 | 66 | List list1 = Arrays.asList("apple", "banana", "orange"); 67 | List list2 = Arrays.asList("banana", "grape", "kiwi"); 68 | List mergedAndDistinct = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toList()); 69 | System.out.println("Merged and distinct list: " + mergedAndDistinct); 70 | 71 | //9. Find the sum of all digits of a number. 72 | 73 | int number = 12345; 74 | int sumOfDigits = String.valueOf(number).chars().map(Character::getNumericValue).sum(); 75 | System.out.println("Sum of digits: " + sumOfDigits); 76 | 77 | 78 | //10. Merge two unsorted arrays into a single sorted array. 79 | 80 | int[] array1 = {5, 2, 8, 1, 7}; 81 | int[] array2 = {4, 9, 3, 6, 10}; 82 | int[] mergedAndSortedArray = Arrays.stream(array1).boxed().sorted().mapToInt(Integer::intValue).toArray(); 83 | System.out.println("Merged and sorted array: " + Arrays.toString(mergedAndSortedArray)); 84 | 85 | //11. Check if two strings are anagrams or not. 86 | 87 | String s1 = "listen"; 88 | String s2 = "silent"; 89 | 90 | s1 = Stream.of(s1.split("")).map(String::toLowerCase).sorted().collect(Collectors.joining()); 91 | s2 = Stream.of(s2.split("")).map(String::toLowerCase).sorted().collect(Collectors.joining()); 92 | if (s1.equals(s2)) 93 | System.out.println("Two strings are anagrams"); 94 | else 95 | System.out.println("Two strings are not anagrams"); 96 | 97 | //12. Reverse each word of a string. 98 | 99 | // String str = "Hello World!"; 100 | String reversedStr = Arrays.stream(str.split(" ")).map(word -> new StringBuffer(word).reverse()).collect(Collectors.joining(" ")); 101 | System.out.println("Reversed String: " + reversedStr); 102 | 103 | //13. Check if a string is palindrome or not. 104 | 105 | // String str = "madam"; 106 | boolean isPalindrome = IntStream.range(0, str.length() / 2) 107 | .noneMatch(index -> str.charAt(index) != str.charAt(str.length() - index - 1)); 108 | if(isPalindrome) 109 | System.out.println(str + " is palindrome"); 110 | else 111 | System.out.println(str + " is not palindrome"); 112 | 113 | 114 | //14. Given a list of lists of strings, flatten it into a single list of unique words. 115 | 116 | List> listOfLists = Arrays.asList( 117 | Arrays.asList("apple", "orange", "banana"), 118 | Arrays.asList("banana", "grape", "kiwi"), 119 | Arrays.asList("orange", "apple", "kiwi")); 120 | List uniqueWords = listOfLists.stream() 121 | .flatMap(List::stream) // Flatten the nested lists 122 | .distinct() // Get unique words 123 | .collect(Collectors.toList()); 124 | System.out.println("Unique words: " + uniqueWords); 125 | 126 | //15. Print fibonacci series. 127 | 128 | int n = 10; 129 | Stream.iterate(new long[]{0, 1}, fib -> new long[]{fib[1], fib[0] + fib[1]}).limit(n).mapToLong(fib -> fib[0]).forEach(System.out::println); 130 | 131 | 132 | } 133 | } -------------------------------------------------------------------------------- /Java8/src/main/java/StreamsPart2_Array.java: -------------------------------------------------------------------------------- 1 | //import java.util.Arrays; 2 | //import java.util.Set; 3 | //import java.util.HashSet; 4 | //import java.util.stream.*; 5 | ///* 6 | // * 7 | // * This code contains top array questions asked in interviews and coding rounds and their solution using Streams API 8 | // * 9 | //*/ 10 | //public class StreamsPart2_Array { 11 | // 12 | // public static void main(String[] args) { 13 | // 14 | // int[] arr1 = {1, 2, 3, 4, 5}; 15 | // int[] arr2 = {1, 2, 3, 4, 5}; 16 | // 17 | // Integer[] numbers = {1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 4, 9, 10, 10}; 18 | // 19 | // //1. How do you check if two arrays are equal or not? 20 | // 21 | // boolean equal = IntStream.range(0, arr1.length).allMatch(i -> arr1[i] == arr2[i]); 22 | // 23 | // System.out.println("Are the arrays equal: " + equal); 24 | // 25 | // /* 26 | // * Time Complexity: O(n), where n is the length of the arrays, as the allMatch() operation iterates over each element in the array stream. 27 | // * 28 | // * Space Complexity: O(1), as the code uses a constant amount of space regardless of the input size. 29 | // * 30 | // * Comparision with traditional approach: Both the streams approach and traditional approach using loops are same in terms of time and space complexity. 31 | // * Both approaches have a time complexity of O(n), where n is the length of the arrays, as they both involve iterating over all elements once. 32 | // * Space complexity for these approaches are also same. 33 | // * 34 | // */ 35 | // 36 | // //2. How do you find duplicate numbers in an array if it contains multiple duplicates? 37 | // 38 | // Set uniqueNumbers = new HashSet<>(); 39 | // Set duplicates = Arrays.stream(numbers).filter(n -> !uniqueNumbers.add(n)).collect(Collectors.toSet()); 40 | // // If not added to the set, it's a duplicate 41 | // System.out.println("Duplicate numbers: " + duplicates); 42 | // 43 | // /* 44 | // * Time Complexity: O(n), where n is the length of the array. 45 | // * 46 | // * Space Complexity: O(k), where k is the number of unique elements in the array. 47 | // * In the worst case, it could be O(n) if all elements are unique. 48 | // * 49 | // * Comparision with traditional approach: The time and space complexities are similar for both approaches. The stream-based approach is more concise and expressive. 50 | // * 51 | // */ 52 | // 53 | // //3. How are duplicates removed from a given array in Java? 54 | // 55 | // Integer[] arrayWithDuplicates = {1, 2, 3, 4, 2, 5, 6, 1, 3}; 56 | // Integer[] uniqueArray = Arrays.stream(arrayWithDuplicates).distinct().toArray(Integer[]::new); 57 | // 58 | // System.out.println("Original array with duplicates: " + Arrays.toString(arrayWithDuplicates)); 59 | // System.out.println("Array with duplicates removed: " + Arrays.toString(uniqueArray)); 60 | // 61 | // /* 62 | // * Time Complexity: O(n), where n is the length of the array 'arrayWithDuplicates'. 63 | // * 64 | // * Space Complexity: O(k), where k is the number of unique elements in 'arrayWithDuplicates' 65 | // * 66 | // * Comparision with traditional approach: The stream-based approach uses the distinct() operation, while the traditional approach uses a HashSet. 67 | // * Both approaches have the same space complexity. The stream-based approach internally uses a set-like structure to track unique elements during processing, and the traditional approach explicitly uses a HashSet. 68 | // * 69 | // */ 70 | // 71 | // //4. How do you merge two sorted arrays into a single sorted array? 72 | // 73 | // int[] mergedArray = IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).sorted().toArray(); 74 | // System.out.println("Merged and sorted array: " + Arrays.toString(mergedArray)); 75 | // 76 | // /* 77 | // * Time Complexity: O((m + n) log(m + n)), where m is the length of array1 and n is the length of array2. 78 | // * 79 | // * Space Complexity: O(m + n), where m is the length of array1 and n is the length of array2. 80 | // * 81 | // * Comparision with traditional approach: Both approaches have the same time and space complexity. The traditional approach with System.arraycopy followed by Arrays.sort might have slightly lower constant factors, potentially making it faster for small to moderately sized arrays. 82 | // * 83 | // */ 84 | // 85 | // //5. Given an array of integers, find all pairs that sum up to a specific target value. 86 | // 87 | // int targetSum = 10; 88 | // 89 | // Arrays.stream(arr1).boxed() 90 | // .flatMap(i -> 91 | // Arrays.stream(arr1) 92 | // .boxed() 93 | // .filter(j -> i + j == targetSum && i <= j) 94 | // .map(j -> new int[]{i, j}) 95 | // ) 96 | // .forEach(pair -> 97 | // System.out.println("Pair with sum " + targetSum + ": " + Arrays.toString(pair)) 98 | // ); 99 | // 100 | // /* 101 | // * Time Complexity: O(n^2), where n is the length of the array. oFr each element in the outer stream, the inner stream iterates over the entire array. 102 | // * 103 | // * Space Complexity: O(1), as no additional data structure is used. 104 | // * 105 | // * Comparision with traditional approach: Both approaches have a time complexity of O(n^2). The traditional approach uses nested loops to solve this problem whereas 106 | // * the stream based approach uses nested stream operations. In terms of time complexity, the optimal approach would be to use a HashSet, instead of using streams or the brute force method. 107 | // * The space complexity for both approaches is O(1) because they do not use additional space. 108 | // * 109 | // */ 110 | // 111 | // 112 | // //6. Rotate an array to the right by a given number of steps. 113 | // 114 | // int[] arr1 = {1, 2, 3, 4, 5}; 115 | // int steps = 2; 116 | // int rotationIndex = arr1.length - steps % arr1.length; 117 | // 118 | // int[] rotatedArray = IntStream.concat(Arrays.stream(Arrays.copyOfRange(arr1, rotationIndex, arr1.length)), 119 | // Arrays.stream(Arrays.copyOfRange(arr1, 0, rotationIndex))).toArray(); 120 | // 121 | // System.out.println("Original Array: " + Arrays.toString(arr1)); 122 | // System.out.println("Rotated Array: " + Arrays.toString(rotatedArray)); 123 | // 124 | // 125 | // /* 126 | // * Time Complexity: O(n), where n is the length of the array. 127 | // * 128 | // * Space Complexity: O(n), where n is the length of the array. This is because this solution creates new arrays for storing the rotated parts, ' 129 | // * and the final rotated array is created by combining these arrays.' 130 | // * 131 | // * Comparision with traditional approach: Both the approaches have linear time complexity of O(n), where n is the length of the array. 132 | // * The stream based approach has space complexity of O(n), whereas the traditional approach has constant space complexity O(1), as it uses in-place array rotation. 133 | // * 134 | // */ 135 | // 136 | // //7. How do you find the intersection of two arrays of integers? 137 | // 138 | // 139 | // int[] intersection = Arrays.stream(arr1).filter(value -> Arrays.stream(arr2).anyMatch(value2 -> value == value2)).distinct().toArray(); 140 | // 141 | // System.out.println("Intersection of arrays: " + Arrays.toString(intersection)); 142 | // 143 | // /* 144 | // * Time Complexity: O(m*n), where m is the length of first array 'arr1' and n is the length of second array 'arr2'. 145 | // * 146 | // * Space Complexity: O(k), where k is the size of the intersection. 147 | // * 148 | // * Comparision with traditional approach: The traditional approach uses sets to find the intersection, and has a time complexity of O(m+n), whereas 149 | // * the stream based approach has a time complexity of O(m*n). 150 | // * The space complexity of the traditional approach is O(min(m, n)), whereas the stream based approach has a complexity of O(k), where k is the size of intersection. 151 | // * Hence, the traditional approach gives a more efficient result. On the other hand, the stream based approach gives a more readable solution. 152 | // * 153 | // */ 154 | // 155 | // //8. How do you perform linear search in a given array? 156 | // 157 | // int target = 7; 158 | // boolean present = Arrays.stream(numbers).anyMatch(element -> element == target); 159 | // 160 | // if (present) { 161 | // System.out.println("Element " + target + "present in the array"); 162 | // } else { 163 | // System.out.println("Element " + target + " not present in the array."); 164 | // } 165 | // 166 | // /* 167 | // * Time Complexity: O(n), where n is the length of the array. 168 | // * 169 | // * Space Complexity: O(n), because of the box() operation. 170 | // * 171 | // * Comparision with traditional approach: Both approaches have similar linear time complexity, as they iterate through the array once. 172 | // * The traditional loop-based method has better space efficiency of O(1). 173 | // * 174 | // */ 175 | // 176 | // 177 | // } 178 | //} 179 | // 180 | // 181 | // 182 | // 183 | -------------------------------------------------------------------------------- /Java8/src/main/java/Student.java: -------------------------------------------------------------------------------- 1 | public class Student { 2 | String name; 3 | int grade; 4 | 5 | @Override 6 | public String toString() { 7 | return "Student{" + 8 | "name='" + name + '\'' + 9 | ", grade=" + grade + 10 | '}'; 11 | } 12 | 13 | public Student(String name, int grade) { 14 | this.name = name; 15 | this.grade = grade; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Java8/src/main/java/assets/Screenshot 2023-07-27 at 11.07.16 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VarshaDas/Java-Code-Snippets/950c4ba8e9c73a9f53dacbf452586ee3cee0d169/Java8/src/main/java/assets/Screenshot 2023-07-27 at 11.07.16 PM.png -------------------------------------------------------------------------------- /LambdasAndStreams/src/main/java/StreamsCodePart2: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.function.Function; 3 | import java.util.stream.Collectors; 4 | import java.util.stream.IntStream; 5 | import java.util.stream.Stream; 6 | 7 | public class StreamsCodeDemoPart2 { 8 | public static void main(String[] args) { 9 | 10 | //1. Given a sentence, find and print the frequency of each word. 11 | String sentence = "Java is a programming language. Java is versatile."; 12 | 13 | Map wordFreqMap = Arrays.stream(sentence.split("\\s+")) 14 | .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); 15 | 16 | 17 | // System.out.println(wordFreqMap); 18 | 19 | //2. Given a list of integers, find out all the numbers starting with 1. 20 | 21 | List nums = Arrays.asList(12, 13, 18, 21, 90, 11); 22 | 23 | List numsWithOne = nums.stream().filter( n -> String.valueOf(n).startsWith("1")).collect(Collectors.toList()); 24 | 25 | // System.out.println(numsWithOne); 26 | 27 | //3. Given a list of names, group them by their first letter, and then count the number of names in each group. 28 | 29 | String[] names = {"Alice", "Bob", "Charlie", "Amy", "Bill", "Anna"}; 30 | 31 | Map namesMap = Arrays.stream(names).collect(Collectors.groupingBy(s -> s.charAt(0), Collectors.counting())); 32 | 33 | // System.out.println(namesMap); 34 | 35 | 36 | // 4. Find and print duplicate numbers in an array if it contains multiple duplicates? 37 | 38 | int[] arr = {2,4,2,3,1,5, 5,78,3,1,5}; 39 | 40 | // Arrays.stream(arr).boxed() 41 | // .collect(Collectors.groupingBy(e-> e, Collectors.counting())) 42 | // .entrySet().stream() 43 | // //key -value - 2 (k), 2(val) 44 | // .filter(entry -> entry.getValue() > 1) 45 | // .map(Map.Entry::getKey) 46 | // .forEach(System.out::println); 47 | 48 | 49 | // 5. How are duplicates removed from a given array in Java? 50 | // 51 | int[] arr2 = {2,4,2,3,1,78}; 52 | 53 | int[] newarr = Arrays.stream(arr).distinct().toArray(); 54 | 55 | // System.out.println(Arrays.toString(newarr)); 56 | 57 | 58 | //6. Given a list of words, filter and print the palindromes 59 | 60 | List strings = List.of("level", "hello", "radar", "world", "deed"); 61 | 62 | List palindromeWords = strings.stream(). 63 | filter(str -> str.equals(new StringBuilder(str).reverse().toString())).collect(Collectors.toList()); 64 | 65 | // System.out.println(palindromeWords); 66 | 67 | 68 | // 7. How do you merge two sorted arrays into a single sorted array? 69 | int[] array1 = {1, 3,32, 5, 7}; 70 | int[] array2 = {2, 4, 6,62, 8}; 71 | 72 | int[] sortedArray = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).sorted().toArray(); 73 | // System.out.println(Arrays.toString(sortedArray)); 74 | 75 | 76 | //8. Given two lists of strings, concatenate them and remove duplicates. 77 | 78 | List list1 = List.of("apple", "banana", "orange"); 79 | List list2 = List.of("banana", "kiwi", "grape"); 80 | 81 | List uniqueList = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toList()); 82 | // System.out.println(uniqueList); 83 | 84 | 85 | // 9. Student Grade Classification - 70 and above pass 86 | 87 | List students = List.of( 88 | new Student("Alice", 85), 89 | new Student("Bob", 60), 90 | new Student("Charlie", 75), 91 | new Student("David", 90) 92 | ); 93 | 94 | 95 | Map> studentMap = 96 | students.stream().collect(Collectors.groupingBy(student -> student.grade >= 70 ? "Pass" : "Fail")); 97 | 98 | // System.out.println(studentMap); 99 | 100 | 101 | //10. Given a list of strings, sort them according to increasing order of their length. 102 | 103 | List fruits = Arrays.asList("Mango","pear" ,"Apple", "Banana", "Pineapple", "Kiwi"); 104 | 105 | fruits.stream().sorted(Comparator.comparingInt(String::length)).forEach(System.out::println); 106 | 107 | 108 | //12.Partition a list of numbers into two groups: even and odd, using a custom predicate. 109 | List numbers1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 110 | Map> partitionedNumbers = numbers1.stream() 111 | .collect(Collectors.partitioningBy(n -> n % 2 == 0)); 112 | 113 | System.out.println(partitionedNumbers); 114 | 115 | //13. Find the squares of the first three even numbers in a list. 116 | 117 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 118 | List firstThreeSquares = numbers.stream() 119 | .filter(n -> n % 2 == 0) 120 | .map(n -> n * n) 121 | .limit(3) 122 | .collect(Collectors.toList()); 123 | 124 | // 14. Flatten a list of lists 125 | 126 | List> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6)); 127 | List flattenedList = listOfLists.stream() 128 | .flatMap(List::stream) 129 | .collect(Collectors.toList()); 130 | 131 | System.out.println(flattenedList); 132 | 133 | 134 | 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /OverridingConcepts/StaticMethodDemo.java: -------------------------------------------------------------------------------- 1 | public class StaticMethodDemo { 2 | public static void main(String[] args) { 3 | System.out.println("main"); 4 | StaticMethodDemo.main(2); 5 | } 6 | 7 | public static void main(int a){ 8 | System.out.println("overloading main"); 9 | } 10 | 11 | public static void main(double a ){ 12 | System.out.println("overloading main"); 13 | } 14 | 15 | 16 | public static void main(String a ){ 17 | System.out.println("overloading main"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Code Examples 2 | 3 | This repository contains a collection of Java code examples that demonstrate various programming concepts, algorithms, and techniques. It serves as a resource for developers to learn and explore Java programming. 4 | 5 | ## Table of Contents 6 | 7 | - [Getting Started](#getting-started) 8 | - [Examples](#examples) 9 | - [Contributing](#contributing) 10 | - [License](#license) 11 | 12 | ## Getting Started 13 | 14 | To get started with these code examples, make sure you have Java Development Kit (JDK) installed on your system. You can download the latest JDK from the official Oracle website or use any other Java development environment of your choice. 15 | 16 | Clone this repository to your local machine using the following command: 17 | 18 | git clone https://github.com/your-username/Java-Code-Examples.git 19 | 20 | ## Examples 21 | 22 | 1. Lambdas and Streams 23 | 2. Arrays and Collections 24 | 3. Comparators 25 | 26 | ## Contributing 27 | 28 | Contributions to this repository are welcome! If you would like to add more code examples, improve existing ones, or suggest new features, please follow these steps: 29 | 30 | 1. Fork the repository. 31 | 2. Create a new branch for your changes. 32 | 3. Make your modifications and additions. 33 | 4. Test your changes to ensure they work as expected. 34 | 5. Commit your changes and push them to your forked repository. 35 | 6. Open a pull request, providing a detailed description of your changes. 36 | 37 | Your contributions will be reviewed, and once approved, they will be merged into the main repository. 38 | 39 | ## License 40 | 41 | This repository is licensed under the [MIT License](LICENSE). You are free to use the code examples, modify them, and distribute them as per the terms of the license. 42 | 43 | --- 44 | 45 | Happy JAVA coding! 46 | --------------------------------------------------------------------------------