0% found this document useful (0 votes)
18 views4 pages

Java Stream API Practice Solutions

The document provides a comprehensive guide on using Java 8 Stream API with various practical examples. It covers operations such as grouping, counting, filtering, and transforming data, along with explanations for each example. Key functionalities demonstrated include finding maximum values, averaging, flattening lists, and handling null values.

Uploaded by

Sai Venkat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

Java Stream API Practice Solutions

The document provides a comprehensive guide on using Java 8 Stream API with various practical examples. It covers operations such as grouping, counting, filtering, and transforming data, along with explanations for each example. Key functionalities demonstrated include finding maximum values, averaging, flattening lists, and handling null values.

Uploaded by

Sai Venkat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 + ")"; }
}
}

Common questions

Powered by AI

The Stream API can create a map associating each unique string with its length by using the 'collect()' method with 'Collectors.toMap()'. The 'toMap()' method requires a key mapper function that maps each element to its key (the string itself) and a value mapper function that maps each string to its length, such as 'String::length'. This generates a map where each string from the input list is associated with its length. For example, with a list of words like "apple", "banana", and "kiwi", a resulting map is {"apple"=5, "banana"=6, "kiwi"=4} .

Flattening a list of lists using the Stream API involves creating a stream of the nested lists and then using 'flatMap()' to convert each sublist into a stream of its elements. By doing so, 'flatMap()' maps each list to a stream and flattens these into a single stream containing all elements. Collect the transformed stream into a list using 'collect(Collectors.toList())'. For example, given a nested list [[1, 2], [3, 4]], the process results in a flattened list [1, 2, 3, 4].

The Stream API concatenates a collection of strings using the 'Collectors.joining()' method, which allows specifying a delimiter. This method melds the elements of the stream into a single string separated by the given delimiter. For example, joining a list of words such as "apple", "banana", and "kiwi" with a comma and space results in the string "apple, banana, kiwi" .

The Java Stream API allows counting occurrences of each character in a string by converting the string into a character stream and then using 'Collectors.groupingBy()' with 'Collectors.counting()'. This involves converting the string into an IntStream of its char values using 'chars()', transforming it to a stream of Character objects via 'mapToObj()', and then collecting the results into a map. Each character is grouped by its identity, and the 'counting()' collector counts the number of occurrences for each character .

The strategy to find the first non-repeating character using the Stream API includes converting the string to a stream of characters, collecting them into a LinkedHashMap with their counts through 'Collectors.groupingBy()', and maintaining insertion order by using 'LinkedHashMap::new'. Then, filter map entries with counts of one and use 'findFirst()' to retrieve the first such character. For the string "stream", this approach identifies 't' as the first non-repeating character .

To find the employee with the highest salary using the Stream API, create a stream from the list of employees using 'stream()'. Use the 'max()' terminal operation, passing a comparator that compares employees based on their salary using 'Comparator.comparingDouble(Employee::getSalary)'. This will produce an optional containing the employee with the highest salary. In the given example, from the employees John ($3000), Jane ($4000), and Doe ($3500), the employee with the highest salary is Jane .

The Stream API enables the removal of null values from a list by using 'filter()' with 'Objects::nonNull', filtering out all null elements. Convert the original list into a stream, apply the filter, and then collect the filtered elements back into a list using 'collect(Collectors.toList())'. For example, removing nulls from the list ["one", null, "two", null, "three"] results in the list ["one", "two", "three"].

Merging two lists with unique elements using the Stream API entails creating streams from each list and concatenating them using 'Stream.concat()'. To ensure uniqueness, apply 'distinct()' to the resultant stream to remove duplicate elements before collecting them into a list with 'collect(Collectors.toList())'. For instance, merging lists [1, 2, 3] and [3, 4, 5] leads to the unique list [1, 2, 3, 4, 5].

To group a list of strings by their length using the Java Stream API, you need to perform the following steps: First, call the 'stream()' method on the list of strings to convert it into a stream. Next, utilize the 'collect()' method with 'Collectors.groupingBy()' to group the elements of the stream according to a classifier function, which in this case is 'String::length'. This will result in a map with keys representing string lengths and values being lists of strings with that length .

The Stream API can be utilized to filter numbers greater than a given threshold and calculate their average by first creating a stream from a list of numbers with the 'stream()' method. Then, employ the 'filter()' method to retain elements that satisfy the condition of being greater than the threshold (e.g., '> 10'). Convert these filtered numbers to an IntStream using 'mapToInt()', allowing for collection of statistical data such as average using the 'average()' method. For example, filtering numbers greater than 10 from the list [5, 15, 25, 3] and finding the average results in 20.0 .

You might also like