Java Stream API Solutions
Java Stream API Solutions
import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
public class StreamPractice {
public static void main(String[] args) {
// 1. Group a list of strings by their length
List<String> words = Arrays.asList("apple", "banana", "kiwi", "orange");
Map<Integer, List<String>> groupedByLength = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println("1. Grouped by Length: " + groupedByLength);
// 2. Count number of occurrences of each character in a string
String input = "stream";
Map<Character, Long> charCount = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("2. Character Counts: " + charCount);
// 3. Find employee with the highest salary
List<Employee> employees = Arrays.asList(
new Employee("John", 3000),
new Employee("Jane", 4000),
new Employee("Doe", 3500)
);
Optional<Employee> highestPaid = employees.stream()
.max(Comparator.comparingDouble(Employee::getSalary));
System.out.println("3. Highest Paid: " + highestPaid.orElse(null));
// 4. Filter numbers > 10 and find average
List<Integer> numbers = Arrays.asList(5, 15, 25, 3);
OptionalDouble avg = numbers.stream()
.filter(n -> n > 10)
.mapToInt(Integer::intValue)
.average();
System.out.println("4. Average >10: " + avg.orElse(0));
// 5. Concatenate strings with commas
String joined = words.stream()
.collect(Collectors.joining(", "));
System.out.println("5. Joined String: " + joined);
// 6. Convert list of strings to map (string -> length)
Map<String, Integer> strLengthMap = words.stream()
.collect(Collectors.toMap(s -> s, String::length));
System.out.println("6. String -> Length Map: " + strLengthMap);
// 7. Flatten a list of lists
List<List<Integer>> nestedList = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4)
);
List<Integer> flatList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println("7. Flattened List: " + flatList);
// 8. Filter transactions of specific type and collect to Set
List<Transaction> transactions = Arrays.asList(
new Transaction("GROCERY"),
new Transaction("ELECTRONICS"),
new Transaction("GROCERY")
);
Set<Transaction> groceryTxns = transactions.stream()
.filter(t -> "GROCERY".equals(t.getType()))
.collect(Collectors.toSet());
System.out.println("8. Grocery Transactions: " + groceryTxns);
// 9. First name of the oldest person
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 40),
new Person("Charlie", 35)
);
String oldestName = people.stream()
.max(Comparator.comparingInt(Person::getAge))
.map(Person::getName)
.orElse("Not Found");
System.out.println("9. Oldest Person: " + oldestName);
// 10. First non-repeating character
Character nonRepeating = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
System.out.println("10. First Non-Repeating Char: " + nonRepeating);
// 11. Sum of squares
int sumSquares = numbers.stream()
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println("11. Sum of Squares: " + sumSquares);
// 12. Skip first 5 elements and print rest
List<Integer> moreNumbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
List<Integer> skipped = moreNumbers.stream()
.skip(5)
.collect(Collectors.toList());
System.out.println("12. Skipped First 5: " + skipped);
// 13. Infinite stream of random numbers, print first 10
System.out.println("13. First 10 Random Numbers:");
new Random().ints().limit(10).forEach(System.out::println);
// 14. Partition integers into even and odd
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("14. Partitioned Even/Odd: " + partitioned);
// 15. Convert to map of length -> list of strings
Map<Integer, List<String>> lengthMap = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println("15. Length -> Strings Map: " + lengthMap);
// 16. Product of all elements
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println("16. Product: " + product);
// 17. Unique words from a list of sentences
List<String> sentences = Arrays.asList("Hello world", "Java streams are powerful");
Set<String> uniqueWords = sentences.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.map(String::toLowerCase)
.collect(Collectors.toSet());
System.out.println("17. Unique Words: " + uniqueWords);
// 18. Filter null values
List<String> nullableList = Arrays.asList("one", null, "two", null, "three");
List<String> nonNullList = nullableList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.out.println("18. Non-null Strings: " + nonNullList);
// 19. Merge two lists and remove duplicates
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(3, 4, 5);
List<Integer> merged = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println("19. Merged Without Duplicates: " + merged);
// 20. Check if any string starts with prefix
boolean startsWithPre = words.stream()
.anyMatch(s -> s.startsWith("a"));
System.out.println("20. Any word starts with 'a': " + startsWithPre);
}
static class Employee {
String name;
double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double getSalary() { return salary; }
@Override
public String toString() {
return name + " (" + salary + ")";
}
}
static class Transaction {
String type;
public Transaction(String type) { this.type = type; }
public String getType() { return type; }
@Override
public String toString() { return type; }
}
static class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() { return age; }
public String getName() { return name; }
@Override
public String toString() { return name + " (" + age + ")"; }
}
}