diff --git a/src/main/java/com/hithomelabs/dsa/Collections/ListExample.java b/src/main/java/com/hithomelabs/dsa/Collections/ListExample.java new file mode 100644 index 0000000..9692f96 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/Collections/ListExample.java @@ -0,0 +1,4 @@ +package com.hithomelabs.dsa.Collections; + +public class List { +} diff --git a/src/main/java/com/hithomelabs/dsa/StreamExecrcise.java b/src/main/java/com/hithomelabs/dsa/StreamExecrcise.java new file mode 100644 index 0000000..393990e --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/StreamExecrcise.java @@ -0,0 +1,278 @@ +package com.hithomelabs.dsa; + + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import java.util.*; +import java.util.function.BinaryOperator; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class StreamExecrcise { + + + public static void main(String[] args){ + + // * * Different questions on streams + // * * Question 1 - 1. Find the Sum of All Elements in a List + + List integers = List.of(1, 2, 3, 4, 5 ,6); + int sum = integers.stream().mapToInt(Integer::intValue).sum(); + //System.out.println(sum); + + // * * Question 2 - Find the Product of All Elements in a List + Optional product = integers.stream().reduce((x, y) -> x*y); + //System.out.println(product); + + // * * Question 3 - Find the Average of All Elements in a List + + Double average = integers.stream().collect(Collectors.averagingInt(Integer::intValue)); + //System.out.println(average); + + // * * Find the maximum element in a list + Optional max = integers.stream().max(Comparator.naturalOrder()); + //System.out.println(max.get()); + + // * * 5. Find the Minimum Element in a List + Optional min = integers.stream().min(Comparator.naturalOrder()); + //System.out.println(min.get()); + + // * * 6. Count the Number of Elements in a List + long count = integers.stream().count(); + //System.out.println(count); + + // * * 7. Check if a List Contains a Specific Element + boolean exists = integers.stream().anyMatch((x) -> x.equals(7)); + //System.out.println(exists); + + // * * 8. Filter Out Even Numbers from a List + List evenList = integers.stream().filter(i -> i%2 == 0).toList(); + //evenList.forEach(System.out::println); + + // * * 9. Filter Out Odd Numbers from a List + List oddList = integers.stream().filter(i -> i % 2 == 1).collect(Collectors.toList()); + //oddList.forEach(System.out::println); + + // * * 10. Convert a List of Strings to Uppercase + List names = List.of("ram", "shyam", "ghanshyam", "parimal", "ajay"); + List upperCaseNames = names.stream().map(String::toUpperCase).collect(Collectors.toList()); + //upperCaseNames.forEach(System.out::println); + + // * * 11. Convert a List of Integers to Their Squares + List integerSquares = integers.stream().map(i -> i * i).collect(Collectors.toList()); + //System.out.println(integerSquares); + + // * * 12. Find the First Element in a List + Optional first = integers.stream().findFirst(); + //System.out.println(first.get()); + + // * * 13. Find the Last Element in a List + Optional lastInteger = integers.stream().reduce((a, b) -> b); + //System.out.println(lastInteger.get()); + + // * * 14. Check if All Elements in a List Satisfy a Condition, they are greater than 1 + boolean greaterThanEqualTo1 = integers.stream().allMatch(x -> x >= 1); + //System.out.println(greaterThanEqualTo1); + + // * * 16. Remove Duplicate Elements from a List + List duplicateNameList = List.of("RAM", "SHYAM", "RAM", "GHANSHYAM", "RAM", "SHYAM"); + List noDuplicatesList = duplicateNameList.stream().distinct().collect(Collectors.toList()); + //System.out.println(noDuplicatesList); + + // * * 17. Sort a List of Integers in Ascending Order + List descendingList = List.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + List ascendingList = descendingList.stream().sorted().collect(Collectors.toUnmodifiableList()); + //System.out.println(ascendingList); + + // * * 18. Sort a List of Integers in Descending Order + List desc = integers.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toUnmodifiableList()); + //System.out.println(desc); + + // * * 19. Sort a List of Strings in Alphabetical Order + List alphabetical = names.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toUnmodifiableList()); + //System.out.println(alphabetical); + + // * * 20. Sort a List of Strings by Their Length + List byLength = names.stream().sorted(Comparator.comparingInt(String::length)).collect(Collectors.toUnmodifiableList()); + //System.out.println(byLength); + + // * * 21. Find the Sum of Digits of a Number + int number = 12345; + int numSum = String.valueOf(number).chars().map(Character::getNumericValue).sum(); + //System.out.println(numSum); + + // * * 22. Factorial of a number + int sample = 5; + int factorial = IntStream.rangeClosed(1, sample).reduce(1, (a, b) -> a * b); + //System.out.println(factorial); + + // * * 23. Find the Second-Largest Element in a List + Optional secodLargest = integers.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst(); + //System.out.println(secodLargest.get()); + + // * * 24. Find the Second-Smallest Element in a List + Optional secondSmallest = descendingList.stream().sorted(Comparator.naturalOrder()).skip(1).findFirst(); + //System.out.println(secondSmallest.get()); + + // * * 25. Find the Longest String in a List + Optional first1 = names.stream().max(Comparator.comparingInt(String::length)); + //System.out.println(first1.get()); + + // * * 26. Find the Shortest String in a List + Optional smalles1 = names.stream().min(Comparator.comparingInt(String::length)); + //System.out.println(smalles1.get()); + + // * * 27. Group a List of Strings by Their Length + + Map> abc = names.stream().collect(Collectors.groupingBy(String::length)); + //System.out.println(abc); + + // * * 28. Group a List of Objects by a Specific Attribute + + @Getter + @Setter + @AllArgsConstructor + class Person { + String name; + int age; + // Constructor, getters, and setters + + @Override + public String toString(){ + return this.name; + } + } + + List people = List.of( + new Person("Alice", 25), + new Person("Bob", 30), + new Person("Charlie", 25) + ); + + + Map> groupedByAge = people.stream() + .collect(Collectors.groupingBy(Person::getAge)); + //System.out.println(groupedByAge); + + // * * 29. Partition a List of Integers into Even and Odd Numbers + Map> map = integers.stream().collect(Collectors.partitioningBy(x -> x % 2 == 0)); + //System.out.println(map); + + // * * 30 Merge 2 lists into a single list + List concatStream = Stream.concat(integers.stream(), descendingList.stream()).toList(); + //concatStream.forEach(System.out::println); + + // * * 31. Find the Intersection of Two Lists + List intersection = descendingList.stream().filter(integers::contains).toList(); + //intersection.forEach(System.out::println); + + // * * 32. Find the Union of Two Lists + List list1 = List.of(100, 99, 98, 97, 96, 100, 99); + Set list1Set = list1.stream().collect(Collectors.toSet()); + + List union = Stream.concat(list1.stream(), integers.stream()).distinct().collect(Collectors.toList()); + //union.forEach(System.out::println); + + // * * 33. Find the Difference Between Two Lists + List difference = descendingList.stream().filter(Predicate.not(integers::contains)).collect(Collectors.toList()); + //difference.forEach(System.out::println); + + // * * 34. Count the Occurrences of Each Element in a List + Map occurences = duplicateNameList.stream().collect(Collectors.groupingBy(x -> x, Collectors.counting())); + //System.out.println(occurences); + + // * * 35. Count the Occurrences of Each Character in a String + String sentence = "Can you count the occurences of each character?"; + Map characterCount = sentence.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + //System.out.println(characterCount); + + // * * 36. Count the Occurrences of Each Word in a String + String sentence2 = "She sells sea shells on the sea shore"; + Map wordOccurences = Arrays.stream(sentence2.split(" ")).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + //System.out.println(wordOccurences); + + // * * 37. Count the Occurrences of Each Vowel in a String + Map vowelCount = "hello world".chars().mapToObj(i -> (char) i).filter(s -> List.of('a', 'e', 'i', 'o', 'u').contains(s)).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + //System.out.println(vowelCount); + + // * * 38. Count the Occurrences of Each Digit in a String + String sentenceWithDigits = "hello 123 world 456"; + Map digitOccurences = sentenceWithDigits.chars().mapToObj(c -> (char) c).filter(Character::isDigit).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + //System.out.println(digitOccurences); + + // * * 39. Reverse a List Using Streams + List reversedList = integers.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> { + Collections.reverse(list); + return list; + })); + //System.out.println(reversedList); + + // * * 40. Reverse a String Using Streams + String reversed = sentence.chars().mapToObj(c -> String.valueOf((char) c)).reduce("", (a,b) -> b + a); + //System.out.println(reversed); + + // * * 41. Find the Most Frequent Element in a List + Optional mostFreq = duplicateNameList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey); + //System.out.println(mostFreq.get()); + + // * * 42. Find the Least Frequent Element in a List + Optional leastFreq = duplicateNameList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().min(Map.Entry.comparingByValue()).map(Map.Entry::getKey); + //System.out.println(leastFreq.get()); + + // * * 43. Find the First Non-Repeated Character in a String + Optional nonRepeatedCharacter = "hello".chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())).entrySet().stream().filter(entry -> entry.getValue() == 1).map(Map.Entry::getKey).findFirst(); + //System.out.println(nonRepeatedCharacter.get()); + + // * * 44. Find the First Repeated Character in a String + Character firstRepeatingCharacter = "helloo".chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())).entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).findFirst().get(); + //System.out.println(firstRepeatingCharacter); + + // * * 45. Check if a String is a Palindrome + String candidate = "madam"; + // * * This crosses a line tbh + boolean result = IntStream.range(0, candidate.length() / 2).allMatch(i -> candidate.charAt(i) == candidate.charAt(candidate.length() - 1 - i)); + //System.out.println(result); + + // * * 47. Generate the Fibonacci Sequence Using Streams + + Stream.iterate(new int[] {0,1}, fib -> new int[]{fib[1], fib[0] + fib[1]}).limit(10).map(fib -> fib[0]); + //.forEach(System.out::println); + + // * * 49. Flatten a List of Lists into a Single List + + List> listOfLists = List.of( + List.of(1, 2, 3), + List.of(4, 5, 6), + List.of(7, 8, 9) + ); + + List flatennedList = listOfLists.stream().flatMap(list -> list.stream()).toList(); + //System.out.println(flatennedList); + + // * * 50. Find the Sum of All Even Numbers in a Nested List + + long sumOfeven = listOfLists.stream().flatMap(List::stream).filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum(); + //System.out.println(sumOfeven); + + // * * 51. Find the Sum of All Odd Numbers in a Nested List + long sumOfOdd = listOfLists.stream().flatMap(List::stream).filter(n -> n % 2 == 1).mapToInt(Integer::intValue).sum(); + //System.out.println(sumOfOdd); + + // * * 55. Find the Shortest Word in a String + String smol = Arrays.stream(sentence2.split(" ")).min(Comparator.comparingInt(String::length)).orElse(""); + //System.out.println(smol); + + // * * 56. Find the Number of Words in a String + long countwords = Arrays.stream(sentence2.split(" ")).count(); + //System.out.println(countwords); + + + } + + +}