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