1. Separate odd and even numbers +
List numbers = Arrays.asList(1,2,3,4,5,6);
Map> result =
numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("Even: " + result.get(true));
System.out.println("Odd: " + result.get(false));
2. Remove duplicate elements +
List list = Arrays.asList(1,2,2,3,4,4);
List unique =
list.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(unique);
3. Frequency of each character +
String str = "hello";
Map freq =
str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
c -> c,
Collectors.counting()));
System.out.println(freq);
4. Frequency of each element in list +
List list = Arrays.asList("a","b","a","c");
Map result =
list.stream()
.collect(Collectors.groupingBy(
e -> e,
Collectors.counting()));
System.out.println(result);
5. Sort decimals in reverse order +
List nums = Arrays.asList(1.2, 3.4, 2.5);
nums.stream()
.sorted(Comparator.reverseOrder())
.forEach(System.out::println);
6. Join a list of strings with prefix and suffix +
List list = Arrays.asList("A", "B", "C");
String result = list.stream()
.collect(Collectors.joining(",", "[", "]"));
System.out.println(result); // [A,B,C]
7. Print multiples of 5 from a list +
List numbers = Arrays.asList(5, 12, 15, 20, 33);
numbers.stream()
.filter(n -> n % 5 == 0)
.forEach(System.out::println);
8. Find maximum and minimum in a list +
List numbers = Arrays.asList(10, 5, 30, 2, 50);
int max = numbers.stream().max(Integer::compare).get();
int min = numbers.stream().min(Integer::compare).get();
System.out.println("Max: " + max);
System.out.println("Min: " + min);
9. Merge two unsorted arrays into a sorted array +
int[] arr1 = {5, 1, 9};
int[] arr2 = {2, 8, 3};
int[] result = IntStream.concat(Arrays.stream(arr1),
Arrays.stream(arr2))
.sorted()
.toArray();
System.out.println(Arrays.toString(result));
10. Merge two arrays into a sorted array without duplicates +
int[] arr1 = {5, 1, 9};
int[] arr2 = {2, 9, 3};
int[] result = IntStream.concat(Arrays.stream(arr1),
Arrays.stream(arr2))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(result));
11. Get three maximum and three minimum numbers +
List numbers = Arrays.asList(10, 5, 30, 2, 50, 40);
List top3 = numbers.stream()
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
List bottom3 = numbers.stream()
.sorted()
.limit(3)
.collect(Collectors.toList());
System.out.println("Top 3: " + top3);
System.out.println("Bottom 3: " + bottom3);
12. Check if two strings are anagrams +
String s1 = "listen";
String s2 = "silent";
boolean isAnagram =
s1.length() == s2.length() &&
s1.chars().sorted()
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString()
.equals(
s2.chars().sorted()
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString());
System.out.println(isAnagram);
13. Find the sum of all digits of a number +
int number = 12345;
int sum = String.valueOf(number)
.chars()
.map(Character::getNumericValue)
.sum();
System.out.println(sum);
14. Find the second largest number in an array +
int[] arr = {10, 20, 5, 30, 25};
int secondLargest = Arrays.stream(arr)
.boxed()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.get();
System.out.println(secondLargest);
15. Sort strings by increasing length +
List list = Arrays.asList("Java", "Stream", "API", "Code");
list.stream()
.sorted(Comparator.comparing(String::length))
.forEach(System.out::println);
16. Find sum and average of array elements +
int[] arr = {10, 20, 30, 40};
int sum = Arrays.stream(arr).sum();
double avg = Arrays.stream(arr).average().getAsDouble();
System.out.println("Sum: " + sum);
System.out.println("Average: " + avg);
17. Find common elements between two arrays +
List list1 = Arrays.asList(1,2,3,4);
List list2 = Arrays.asList(3,4,5,6);
List common = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println(common);
18. Reverse each word of a string +
String input = "Java Stream API";
String result = Arrays.stream(input.split(" "))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
System.out.println(result);
19. Find the sum of first 10 natural numbers +
int sum = IntStream.rangeClosed(1, 10).sum();
System.out.println(sum);
20. Reverse an integer array +
int[] arr = {1,2,3,4,5};
int[] reversed = IntStream.rangeClosed(1, arr.length)
.map(i -> arr[arr.length - i])
.toArray();
System.out.println(Arrays.toString(reversed));
21. Print the first 10 even numbers +
IntStream.iterate(2, n -> n + 2)
.limit(10)
.forEach(System.out::println);
22. Find the most repeated element in an array +
List list = Arrays.asList(1,2,2,3,3,3,4);
Integer mostFrequent = list.stream()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.get()
.getKey();
System.out.println(mostFrequent);
23. Check if a string is a palindrome +
String str = "madam";
boolean isPalindrome =
IntStream.range(0, str.length()/2)
.noneMatch(i -> str.charAt(i) != str.charAt(str.length()-i-1));
System.out.println(isPalindrome);
24. Find strings starting with a number +
List list = Arrays.asList("1abc", "abc", "2xyz");
list.stream()
.filter(s -> !s.isEmpty() && Character.isDigit(s.charAt(0)))
.forEach(System.out::println);
25. Extract duplicate elements from an array +
List list = Arrays.asList(1,2,2,3,4,4,5);
Set duplicates = list.stream()
.filter(e -> Collections.frequency(list, e) > 1)
.collect(Collectors.toSet());
System.out.println(duplicates);
26. Print duplicate characters in a string +
String str = "programming";
Set duplicates = str.chars()
.mapToObj(c -> (char)c)
.filter(c -> str.indexOf(c) != str.lastIndexOf(c))
.collect(Collectors.toSet());
System.out.println(duplicates);
27. Find the first repeated character in a string +
String str = "programming";
Character firstRepeated = str.chars()
.mapToObj(c -> (char)c)
.filter(c -> str.indexOf(c) != str.lastIndexOf(c))
.findFirst()
.get();
System.out.println(firstRepeated);
28. Find the first non-repeated character in a string +
String str = "programming";
Character firstNonRepeated = str.chars()
.mapToObj(c -> (char)c)
.filter(c -> str.indexOf(c) == str.lastIndexOf(c))
.findFirst()
.get();
System.out.println(firstNonRepeated);
29. Generate the Fibonacci series +
Stream.iterate(new int[]{0,1},
t -> new int[]{t[1], t[0] + t[1]})
.limit(10)
.map(t -> t[0])
.forEach(System.out::println);
30. Print the first 10 odd numbers +
IntStream.iterate(1, n -> n + 2)
.limit(10)
.forEach(System.out::println);
31. Get the last element of an array +
int[] arr = {10,20,30,40};
int last = Arrays.stream(arr)
.reduce((first, second) -> second)
.getAsInt();
System.out.println(last);
32. Calculate age in years +
LocalDate birthDate = LocalDate.of(1995, 5, 10);
int age = Period.between(birthDate, LocalDate.now()).getYears();
System.out.println(age);
33. Extract unique strings starting with # +
List list = Arrays.asList("#java", "#stream", "hello", "#java");
list.stream()
.filter(s -> s.startsWith("#"))
.distinct()
.forEach(System.out::println);