diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5556663 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +.idea +target \ No newline at end of file diff --git a/LambdasAndStreams/.gitignore b/LambdasAndStreams/.gitignore new file mode 100644 index 0000000..bbaaba9 --- /dev/null +++ b/LambdasAndStreams/.gitignore @@ -0,0 +1,4 @@ +# Default ignored files +.idea +target +.class \ No newline at end of file diff --git a/LambdasAndStreams/pom.xml b/LambdasAndStreams/pom.xml new file mode 100644 index 0000000..0e8e0e0 --- /dev/null +++ b/LambdasAndStreams/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + org.example + Java8 + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 16 + 16 + + + + + + \ No newline at end of file diff --git a/LambdasAndStreams/src/main/java/StreamsCodeDemoPart2.java b/LambdasAndStreams/src/main/java/StreamsCodeDemoPart2.java new file mode 100644 index 0000000..abc2441 --- /dev/null +++ b/LambdasAndStreams/src/main/java/StreamsCodeDemoPart2.java @@ -0,0 +1,211 @@ +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +/** + * Class to demonstrate Streams, record and generics in Java. + */ +public class StreamsCodeDemoPart2 { + // Enable this to see logs. + private static final boolean DEBUG = true; + + public static void main(String[] args) { + + // 1. Given a sentence, find and print the frequency of each word. + String sentence = "Java is a programming language. Java is versatile. Java is fun!"; + + Map wordFreqMap = Arrays.stream(sentence.split("\\s+")) + .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); + + printArgs(wordFreqMap); + + // 2. Given a list of integers, find out all the numbers starting with 1. + + List numList = Arrays.asList(12, 13, 18, 21, 90, 11); + + List numbersWithOne = numList.stream() + .filter(n -> String.valueOf(n).startsWith("1")) + .toList(); + + printArgs(numbersWithOne); + + // 3. Given a list of names, group them by their first letter, and then count the number of names in each group. + + String[] names = {"Alice", "Bob", "Charlie", "Amy", "Bill", "Anna", "John", "Michael", "Rambo", "Batman"}; + + Map namesMap = Arrays.stream(names) + .collect(Collectors.groupingBy(s -> s.charAt(0), Collectors.counting())); + + printArgs(namesMap); + + // 4. Find and print duplicate numbers in an array if it contains multiple duplicates? + + int[] arr = {2, 4, 2, 3, 1, 5, 5, 78, 3, 1, 5}; + + Arrays.stream(arr).boxed() + .collect(Collectors.groupingBy(e -> e, Collectors.counting())) + .entrySet().stream() + //key -value - 2 (k), 2(val) + .filter(entry -> entry.getValue() > 1) + .map(Map.Entry::getKey) + .forEach(StreamsCodeDemoPart2::printArgs); + + // 5. How are duplicates removed from a given array in Java? + + int[] newArr = Arrays.stream(arr).distinct().toArray(); + + printArgs(newArr); + + // 6. Given a list of words, filter and print the palindromes + + List strings = List.of("level", "hello", "radar", "world", "deed"); + + List palindromeWords = strings.stream(). + filter(str -> str.contentEquals(new StringBuilder(str).reverse())).toList(); + + printArgs(palindromeWords); + + // 7. How do you merge two sorted arrays into a single sorted array? + int[] array1 = {1, 3, 32, 5, 7}; + int[] array2 = {2, 4, 6, 62, 8}; + + int[] sortedArray = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).sorted().toArray(); + printArgs(sortedArray); + + // 8. Given two lists of strings, concatenate them and remove duplicates. + + List list1 = List.of("apple", "banana", "orange"); + List list2 = List.of("banana", "kiwi", "grape"); + + List uniqueList = Stream + .concat(list1.stream(), list2.stream()) + .distinct() + .toList(); + printArgs(uniqueList); + + // 9. Student Grade Classification - 70 and above pass + + List students = List.of( + new Student("Alice", 85), + new Student("Bob", 60), + new Student("Charlie", 75), + new Student("David", 90) + ); + + Map> studentMap = + students.stream().collect(Collectors.groupingBy(student -> student.grade >= 70 ? "Pass" : "Fail")); + + printArgs(studentMap); + + // 10. Given a list of strings, sort them according to increasing order of their length. + + List fruits = Arrays.asList("Mango", "pear", "Apple", "Banana", "Pineapple", "Kiwi"); + + fruits.stream().sorted(Comparator.comparingInt(String::length)).forEach(StreamsCodeDemoPart2::printArgs); + + // 11.Partition a list of numbers into two groups: even and odd, using a custom predicate. + List numbers1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Map> partitionedNumbers = numbers1.stream() + .collect(Collectors.partitioningBy(n -> n % 2 == 0)); + + printArgs(partitionedNumbers); + + // 12. Find the squares of the first three even numbers in a list. + + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + List firstThreeSquares = numbers.stream() + .filter(n -> n % 2 == 0) + .map(n -> n * n) + .limit(3) + .toList(); + + printArgs(firstThreeSquares); + + // 13. Flatten a list of lists + + List> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6)); + List flattenedList = listOfLists.stream() + .flatMap(List::stream) + .toList(); + + printArgs(flattenedList); + + // 14. Find prime numbers in a given array. + + int[] primeInputList = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 29, 30}; + + printArgs( + Arrays.stream(primeInputList) + .filter(StreamsCodeDemoPart2::isPrime) + .sorted() + ); + + // 15. String array to Map with String length as the key. Re-using fruits List here. :) + + printArgs( + fruits.stream() + .collect( + Collectors.toMap( + Function.identity(), + String::length + ) + ) + ); + + // 16. Find the topper in the list of students. Re-using students here. + Optional topper = students.stream() + .max(Comparator.comparingInt(student -> student.grade)); + + topper.ifPresent(StreamsCodeDemoPart2::printArgs); + } + + /** + * Helper method for printing the logs. + * This makes it easy to enable or disable logs. + * + * @param message Generic type to be printed. It could be a String, a List, or a Map. + */ + private static void printArgs(V message) { + if (DEBUG) { + System.out.println(message); + } else { + System.out.println("Please change 'DEBUG' to true to see logs."); + } + } + + /** + * Method to check if the given number is prime or not. + * + * @param number int input for checking prime number. + * @return true if prime, false otherwise. + */ + private static boolean isPrime(int number) { + if (number <= 1) { + return false; + } + + for (int i = 2; i <= Math.sqrt(number); i++) { + if (number % i == 0) + return false; + } + return true; + } + + /** + * Record to template a student's name and grade. + * + * @param name String name of the student. + * @param grade int grade of the student. + */ + private record Student(String name, int grade) { + @Override + public String toString() { + return "Student{" + + "name='" + name + '\'' + + ", grade=" + grade + + '}'; + } + } +} diff --git a/LambdasAndStreams/src/main/java/StreamsCodePart2 b/LambdasAndStreams/src/main/java/StreamsCodePart2 deleted file mode 100644 index 0fda2ab..0000000 --- a/LambdasAndStreams/src/main/java/StreamsCodePart2 +++ /dev/null @@ -1,136 +0,0 @@ -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public class StreamsCodeDemoPart2 { - public static void main(String[] args) { - - //1. Given a sentence, find and print the frequency of each word. - String sentence = "Java is a programming language. Java is versatile."; - - Map wordFreqMap = Arrays.stream(sentence.split("\\s+")) - .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); - - -// System.out.println(wordFreqMap); - - //2. Given a list of integers, find out all the numbers starting with 1. - - List nums = Arrays.asList(12, 13, 18, 21, 90, 11); - - List numsWithOne = nums.stream().filter( n -> String.valueOf(n).startsWith("1")).collect(Collectors.toList()); - -// System.out.println(numsWithOne); - - //3. Given a list of names, group them by their first letter, and then count the number of names in each group. - - String[] names = {"Alice", "Bob", "Charlie", "Amy", "Bill", "Anna"}; - - Map namesMap = Arrays.stream(names).collect(Collectors.groupingBy(s -> s.charAt(0), Collectors.counting())); - -// System.out.println(namesMap); - - - // 4. Find and print duplicate numbers in an array if it contains multiple duplicates? - - int[] arr = {2,4,2,3,1,5, 5,78,3,1,5}; - -// Arrays.stream(arr).boxed() -// .collect(Collectors.groupingBy(e-> e, Collectors.counting())) -// .entrySet().stream() -// //key -value - 2 (k), 2(val) -// .filter(entry -> entry.getValue() > 1) -// .map(Map.Entry::getKey) -// .forEach(System.out::println); - - - // 5. How are duplicates removed from a given array in Java? -// - int[] arr2 = {2,4,2,3,1,78}; - - int[] newarr = Arrays.stream(arr).distinct().toArray(); - -// System.out.println(Arrays.toString(newarr)); - - - //6. Given a list of words, filter and print the palindromes - - List strings = List.of("level", "hello", "radar", "world", "deed"); - - List palindromeWords = strings.stream(). - filter(str -> str.equals(new StringBuilder(str).reverse().toString())).collect(Collectors.toList()); - -// System.out.println(palindromeWords); - - - // 7. How do you merge two sorted arrays into a single sorted array? - int[] array1 = {1, 3,32, 5, 7}; - int[] array2 = {2, 4, 6,62, 8}; - - int[] sortedArray = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).sorted().toArray(); -// System.out.println(Arrays.toString(sortedArray)); - - - //8. Given two lists of strings, concatenate them and remove duplicates. - - List list1 = List.of("apple", "banana", "orange"); - List list2 = List.of("banana", "kiwi", "grape"); - - List uniqueList = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toList()); -// System.out.println(uniqueList); - - - // 9. Student Grade Classification - 70 and above pass - - List students = List.of( - new Student("Alice", 85), - new Student("Bob", 60), - new Student("Charlie", 75), - new Student("David", 90) - ); - - - Map> studentMap = - students.stream().collect(Collectors.groupingBy(student -> student.grade >= 70 ? "Pass" : "Fail")); - -// System.out.println(studentMap); - - - //10. Given a list of strings, sort them according to increasing order of their length. - - List fruits = Arrays.asList("Mango","pear" ,"Apple", "Banana", "Pineapple", "Kiwi"); - - fruits.stream().sorted(Comparator.comparingInt(String::length)).forEach(System.out::println); - - - //12.Partition a list of numbers into two groups: even and odd, using a custom predicate. - List numbers1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - Map> partitionedNumbers = numbers1.stream() - .collect(Collectors.partitioningBy(n -> n % 2 == 0)); - - System.out.println(partitionedNumbers); - - //13. Find the squares of the first three even numbers in a list. - - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - List firstThreeSquares = numbers.stream() - .filter(n -> n % 2 == 0) - .map(n -> n * n) - .limit(3) - .collect(Collectors.toList()); - - // 14. Flatten a list of lists - - List> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6)); - List flattenedList = listOfLists.stream() - .flatMap(List::stream) - .collect(Collectors.toList()); - - System.out.println(flattenedList); - - - - } -}