Java program to calculate sum of squares of odd and even numbers using lambda expression
Java Lambda Program: Exercise-15 with Solution
Write a Java program to implement a lambda expression to calculate the sum of squares of all odd and even numbers in a list.
Sample Solution:
Java Code:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of integers
List < Integer > nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Original list elements: " + nums);
// Calculate the sum of squares of odd numbers using lambda expression
int sum_squares_odd = nums.stream()
.filter(n -> n % 2 != 0)
.mapToInt(n -> n * n)
.sum();
// Calculate the sum of squares of even numbers using lambda expression
int sum_squares_even = nums.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();
// Print the results
System.out.println("\nSum of squares of odd numbers: " + sum_squares_odd);
System.out.println("\nSum of squares of even numbers: " + sum_squares_even);
}
}
Sample Output:
Original list elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Sum of squares of odd numbers: 165 Sum of squares of even numbers: 220
Explanation:
The necessary classes are imported: Arrays and Lists.
In the main method, we create a list of integers called nums using Arrays.asList().
A lambda expression is used to calculate the sum of squares of odd numbers:
- Use the stream() method to create a stream of integers from the nums list.
- Use the filter() method to filter out odd numbers by checking if the remainder of dividing the number by 2 is not equal to 0.
- Use the mapToInt() method to square each odd number.
- Use the sum() method to calculate the sum of squares of odd numbers.
- Store the result in the variable sum_squares_odd.
A similar lambda expression is used to calculate the sum of squares of even numbers:
- Use the filter() method to filter out even numbers by checking if the remainder of dividing the number by 2 is equal to 0.
- Store the result in the variable sum_squares_even.
Finally, System.out.println() function prints the result.
Flowchart:

Live Demo:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Java Lambda Exercises Previous: Java program to check Palindrome string using lambda expression.
Java Lambda Exercises Next: Java program to check if a list contains a specific word using lambda expression.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Hashset vs Treeset:
HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet.
HashSet
- the class offers constant time performance for the basic operations (add, remove, contains and size).
- it does not guarantee that the order of elements will remain constant over time
- iteration performance depends on the initial capacity and the load factor of the HashSet.
- It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.
TreeSet
- guarantees log(n) time cost for the basic operations (add, remove and contains)
- guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via its constructor) (implements SortedSet)
- doesn't offer any tuning parameters for iteration performance
- offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc
Important points:
- Both guarantee duplicate-free collection of elements
- It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
- None of these implementations are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
- LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however,it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.
So a choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet.
- e.g. SortedSet<String> s = new TreeSet<String>(hashSet);
Ref: https://bit.ly/3d3waGh
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook