0% found this document useful (0 votes)
6 views9 pages

Java Stream Operations for Beginners

The document provides various examples of using Java Streams to manipulate collections, including filtering, sorting, counting, and transforming data. It covers operations such as printing even numbers, finding strings that start with a specific letter, sorting lists, and grouping elements. Additionally, it explains advanced concepts like partitioning and counting distinct characters.

Uploaded by

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

Java Stream Operations for Beginners

The document provides various examples of using Java Streams to manipulate collections, including filtering, sorting, counting, and transforming data. It covers operations such as printing even numbers, finding strings that start with a specific letter, sorting lists, and grouping elements. Additionally, it explains advanced concepts like partitioning and counting distinct characters.

Uploaded by

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

Beginner Level

1. Given a list of integers, print only even numbers using Streams.


List<Integer> numbers = [Link](10, 15, 20, 25, 30);

List<Integer> a=[Link]() .filter(n -> n % 2 == 0).collect([Link]());

2. From a list of strings, find all strings that start with "A".
List<String> names = [Link]("Apple", "Banana", "Avocado", "Mango");

List<String> startsWithA = [Link]() .filter(s -> [Link]("A"))


.collect([Link]());

3. Given an array of integers, count how many numbers are greater


than 50.4
int[] arr = {10, 55, 72, 43, 90, 15};

long count = [Link](arr).filter(n -> n > 50).count();


//As Count is single it will be Count and not list of count
//Count always is Long

4. Sort a list of names in alphabetical order using Streams or


ascending Order

List<String> names = [Link]("John", "Alice", "Bob", "David");

List<String> sorted = [Link]().sorted().collect([Link]());

By default putting a sorted() will sort in ascending order


2. Sort list of integers in descending order

List<Integer> numbers = [Link](5, 1, 9, 3, 7);

List<Integer> sortedDesc = [Link]().sorted([Link]())


.collect([Link]());

[Link](sortedDesc); // [9, 7, 5, 3, 1]

4. Sort strings by length (ascending)

List<String> names = [Link]("John", "Alice", "Bob", "Alexander");

List<String> sortedByLengthDesc =
[Link]() .sorted([Link](String::length).reversed())
.collect([Link]());

[Link](sortedByLengthDesc); // [Alexander, Alice, John, Bob]

6. Sort list of employees by salary (ascending) imp

class Employee {

String name;

int salary;

Employee(String name, int salary) { [Link] = name; [Link] = salary; }

public String toString() { return name + " - " + salary; }

List<Employee> employees = [Link](

new Employee("John", 5000),


new Employee("Alice", 7000),

new Employee("Bob", 4000)

);

List<Employee> sortedBySalary =
[Link]() .sorted([Link](e ->
[Link])) .collect([Link]());

Over here the highlighted on is .comparing int and then accessing salary because it is int

For Double it will be ([Link](e -> [Link]))

Similarly for String comparison it should be

List<Employee> sortedByName =
[Link]() .sorted([Link](e -> [Link]))
.collect([Link]());

VV IMP

If want to sort using 2 conditions then

List<Employee> sortedBySalaryThenName = [Link]()

.sorted([Link]((Employee e) -> [Link])

.thenComparing(e -> [Link]))

.collect([Link]());

Sort employees by salary (descending) then by name (ascending)

List<Employee> sortedCustom = [Link]()

.sorted([Link]((Employee e) -> [Link]).reversed()

.thenComparing(e -> [Link]))

.collect([Link]());
5. Convert a list of integers into a list of their squares.
List<Integer> numbers = [Link](2, 3, 4, 5);

List<Integer> squares = [Link]().map(n -> n *


n) .collect([Link]());

HOW TO MAKE IN UPPERCASE

List<String> sortedUppercase = [Link]()

.map(String::toUppercase)

.collect([Link]());

The :: operator in Java 8 is known as the Method Reference operator. It


provides a concise way to refer to methods or constructors without invoking
them, acting as a shorthand for certain lambda expressions.

Intermediate

: Find the first element in a list

List<Integer> numbers = [Link](10, 20, 30, 40, 50);

[Link]().findFirst().ifPresent([Link]::println); // Output: 10

Find the Last element in a list


Optional<Integer> last = [Link]().skip([Link]() - 1).findFirst();

check if list contains any word with length > 10

List<String> words = [Link]("Java", "ProgrammingLanguage", "Stream", "API");

boolean result = [Link]()

.anyMatch(s -> [Link]() > 10);

[Link](result); // Output: true

Find maximum and minimum values


List<Integer> numbers = [Link](10, 55, 72, 43, 90, 15);

int max = [Link]()

.max(Integer::compare)

.get();

int min = [Link]()

.min(Integer::compare)

.get();
[Link]("Max: " + max); // 90

[Link]("Min: " + min); // 10

Problem 9: Join strings with commas

List<String> languages = [Link]("Java", "Python", "C++", "Go");

String result = [Link]()

.collect([Link](", "));

[Link](result); // Java, Python, C++, Go

Problem 10: Convert words into list of unique characters


List<String> words = [Link]("Java", "Python");

List<String> uniqueChars = [Link]()


.flatMap(word -> [Link]().mapToObj(c -> [Link]((char) c)))
.distinct()
.collect([Link]());

[Link](uniqueChars);
// Output: [J, a, v, P, y, t, h, o, n]

Imp difference

[Link]()
● Groups elements based on a classifier function (key).

● Key can have many possible values.


● Output is a Map<K, List<T>> (or Map<K, something else if you use downstream
collectors).

List<String> words = [Link]("Java", "Spring", "API", "Code");

Map<Integer, List<String>> grouped = [Link]()

.collect([Link](String::length));

[Link](grouped);

// {3=[API], 4=[Java, Code], 6=[Spring]}

[Link]()
Special case of groupingBy.

Divides elements into two groups only (true/false).

Output is a Map<Boolean, List<T>>.

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);

Map<Boolean, List<Integer>> partitioned = [Link]()

.collect([Link](n -> n % 2 == 0));

[Link](partitioned);

// {false=[1, 3, 5], true=[2, 4, 6]}

Group words by their length


List<String> words = [Link]("apple", "banana", "cat", "dog", "elephant", "fish");

Map<Integer, List<String>> grouped = [Link]()

.collect([Link](String::length));
[Link](grouped);

// {3=[cat, dog], 4=[fish], 5=[apple], 6=[banana], 8=[elephant]}

Partition numbers into odd and even

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Map<Boolean, List<Integer>> partitioned = [Link]()

.collect([Link](n -> n % 2 == 0));

[Link]("Even: " + [Link](true));

[Link]("Odd: " + [Link](false));

Count character frequecy

List<String> words = [Link]("hello", "world");

long distinctCount = [Link]()

.flatMap(word -> [Link]().mapToObj(c -> (char) c))

.distinct()

.count();

[Link]("Distinct characters count: " + distinctCount);

You might also like