Adding stream exercise

This commit is contained in:
hitanshu310 2026-01-11 15:46:43 +05:30
parent 52ee8d1b90
commit 688b1a9127
2 changed files with 282 additions and 0 deletions

View File

@ -0,0 +1,4 @@
package com.hithomelabs.dsa.Collections;
public class List {
}

View File

@ -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<Integer> 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<Integer> 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<Integer> max = integers.stream().max(Comparator.naturalOrder());
//System.out.println(max.get());
// * * 5. Find the Minimum Element in a List
Optional<Integer> 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<Integer> evenList = integers.stream().filter(i -> i%2 == 0).toList();
//evenList.forEach(System.out::println);
// * * 9. Filter Out Odd Numbers from a List
List<Integer> 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<String> names = List.of("ram", "shyam", "ghanshyam", "parimal", "ajay");
List<String> upperCaseNames = names.stream().map(String::toUpperCase).collect(Collectors.toList());
//upperCaseNames.forEach(System.out::println);
// * * 11. Convert a List of Integers to Their Squares
List<Integer> integerSquares = integers.stream().map(i -> i * i).collect(Collectors.toList());
//System.out.println(integerSquares);
// * * 12. Find the First Element in a List
Optional<Integer> first = integers.stream().findFirst();
//System.out.println(first.get());
// * * 13. Find the Last Element in a List
Optional<Integer> 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<String> duplicateNameList = List.of("RAM", "SHYAM", "RAM", "GHANSHYAM", "RAM", "SHYAM");
List<String> noDuplicatesList = duplicateNameList.stream().distinct().collect(Collectors.toList());
//System.out.println(noDuplicatesList);
// * * 17. Sort a List of Integers in Ascending Order
List<Integer> descendingList = List.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
List<Integer> ascendingList = descendingList.stream().sorted().collect(Collectors.toUnmodifiableList());
//System.out.println(ascendingList);
// * * 18. Sort a List of Integers in Descending Order
List<Integer> desc = integers.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toUnmodifiableList());
//System.out.println(desc);
// * * 19. Sort a List of Strings in Alphabetical Order
List<String> alphabetical = names.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toUnmodifiableList());
//System.out.println(alphabetical);
// * * 20. Sort a List of Strings by Their Length
List<String> 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<Integer> secodLargest = integers.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst();
//System.out.println(secodLargest.get());
// * * 24. Find the Second-Smallest Element in a List
Optional<Integer> secondSmallest = descendingList.stream().sorted(Comparator.naturalOrder()).skip(1).findFirst();
//System.out.println(secondSmallest.get());
// * * 25. Find the Longest String in a List
Optional<String> first1 = names.stream().max(Comparator.comparingInt(String::length));
//System.out.println(first1.get());
// * * 26. Find the Shortest String in a List
Optional<String> smalles1 = names.stream().min(Comparator.comparingInt(String::length));
//System.out.println(smalles1.get());
// * * 27. Group a List of Strings by Their Length
Map<Integer, List<String>> 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<Person> people = List.of(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25)
);
Map<Integer, List<Person>> groupedByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
//System.out.println(groupedByAge);
// * * 29. Partition a List of Integers into Even and Odd Numbers
Map<Boolean, List<Integer>> map = integers.stream().collect(Collectors.partitioningBy(x -> x % 2 == 0));
//System.out.println(map);
// * * 30 Merge 2 lists into a single list
List<Integer> concatStream = Stream.concat(integers.stream(), descendingList.stream()).toList();
//concatStream.forEach(System.out::println);
// * * 31. Find the Intersection of Two Lists
List<Integer> intersection = descendingList.stream().filter(integers::contains).toList();
//intersection.forEach(System.out::println);
// * * 32. Find the Union of Two Lists
List<Integer> list1 = List.of(100, 99, 98, 97, 96, 100, 99);
Set<Integer> list1Set = list1.stream().collect(Collectors.toSet());
List<Integer> union = Stream.concat(list1.stream(), integers.stream()).distinct().collect(Collectors.toList());
//union.forEach(System.out::println);
// * * 33. Find the Difference Between Two Lists
List<Integer> 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<String, Long> 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<Character, Long> 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<String, Long> 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<Character, Long> 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<Character, Long> 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<Integer> 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<String> 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<String> 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<Character> 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<List<Integer>> listOfLists = List.of(
List.of(1, 2, 3),
List.of(4, 5, 6),
List.of(7, 8, 9)
);
List<Integer> 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);
}
}