The document provides an overview of Java's Comparator interface for sorting objects, demonstrating its use with a Person class sorted by age. It also covers filtering collections using streams, generating streams from lists, and creating infinite streams with iterate and generate methods. Additionally, it shows how to process streams for various operations like counting and filtering elements.
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 ratings0% found this document useful (0 votes)
4 views9 pages
Comparator Filter Stream
The document provides an overview of Java's Comparator interface for sorting objects, demonstrating its use with a Person class sorted by age. It also covers filtering collections using streams, generating streams from lists, and creating infinite streams with iterate and generate methods. Additionally, it shows how to process streams for various operations like counting and filtering elements.
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/ 9
Comparator
a Comparator is used to define how two objects should be compared or
sorted. You use it when you want to control how a list of objects is ordered. import java.util.*; //continuation import java.util.Comparator; public class Main { public static void main(String[] args) { class Person { List<Person> people = new ArrayList<>(); String name; people.add(new Person("Alice", 30)); int age; people.add(new Person("Bob", 25)); people.add(new Person("Charlie", 35)); Person(String name, int age) { this.name = name; // Sort people by age using AgeComparator this.age = age; Collections.sort(people, new } AgeComparator()); } // Print sorted list class AgeComparator implements Comparator<Person> { for (Person p : people) { public int compare(Person p1, Person p2) { System.out.println(p.name + " is " + p.age + " // Compare the two people by their age years old"); return p1.age - p2.age; } } } } } Filter Collections you can filter a collection (like a List or a Set ) to only keep elements that meet certain conditions ) Program
System.out.println(evenNumbers); } } Generation of streams Streams refer to a sequence of elements that can be processed in a functional style. They allow you to perform complex operations like filtering, mapping, and reducing data in a clean and readable way import java.util.*; import java.util.stream.*;
nameStream.filter(name -> name.startsWith("A")) .forEach(System.out::println); // Output: Alice } } .iterate(seed,next)
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) { // Generate an infinite stream of numbers starting from 0 Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 1);
// Limit the stream to the first 10 numbers and print them