0% found this document useful (0 votes)
2 views2 pages

Java 8 Streams Assignment

Uploaded by

suriyajai2007
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)
2 views2 pages

Java 8 Streams Assignment

Uploaded by

suriyajai2007
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
You are on page 1/ 2

Java 8 Streams Mini Assignment with Answers

Q1: Filter Even Numbers

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

numbers.stream()

.filter(n -> n % 2 == 0)

.forEach(System.out::println);

Q2: Convert Strings to Uppercase

List<String> names = Arrays.asList("jai", "suriya", "kumar");

List<String> upperNames = names.stream()

.map(String::toUpperCase)

.collect(Collectors.toList());

System.out.println(upperNames); // [JAI, SURIYA, KUMAR]

Q3: Get Squares of Numbers

List<Integer> nums = Arrays.asList(2, 3, 4);

List<Integer> squares = nums.stream()

.map(n -> n * n)

.collect(Collectors.toList());

System.out.println(squares); // [4, 9, 16]

Q4: Sum All Numbers

List<Integer> nums = Arrays.asList(1, 2, 3, 4);

int sum = nums.stream()

.reduce(0, Integer::sum);

System.out.println(sum); // 10

Q5: Sort Numbers

List<Integer> nums = Arrays.asList(5, 1, 4, 2, 3);

nums.stream()

.sorted()

.forEach(System.out::println);

Q6: Remove Duplicates


List<Integer> nums = Arrays.asList(1, 2, 2, 3, 4, 4, 5);

nums.stream()

.distinct()

.forEach(System.out::println);

Q7: Limit Output

List<String> names = Arrays.asList("Ram", "Sita", "Ravi", "Radha", "Gita");

names.stream()

.limit(3)

.forEach(System.out::println);

Q8: Skip First 2 Items

List<String> names = Arrays.asList("Ram", "Sita", "Ravi", "Radha");

names.stream()

.skip(2)

.forEach(System.out::println);

Q9: Check if Any Name Starts with 'R'

List<String> names = Arrays.asList("Geeta", "Sita", "Ravi", "Radha");

boolean result = names.stream()

.anyMatch(name -> name.startsWith("R"));

System.out.println(result); // true

Q10: Count Names with 4 Letters

List<String> names = Arrays.asList("Ram", "Ravi", "Lina", "Geet", "Kavi");

long count = names.stream()

.filter(name -> name.length() == 4)

.count();

System.out.println(count); // 3

You might also like