Skip to content

Instantly share code, notes, and snippets.

@skryvets
Last active April 8, 2021 21:48
Show Gist options
  • Save skryvets/f7014e733a0fe05c18723a59ceecbecc to your computer and use it in GitHub Desktop.
Save skryvets/f7014e733a0fe05c18723a59ceecbecc to your computer and use it in GitHub Desktop.
Stream filter and sort example
/*
In this scenario we create twenty random cars (random model and year).
An expected result is to only get Toyota and sort by year, newest first.
*/
class Scratch {
public static void main(String[] args) {
List<Car> cars = CarFactory.createTwentyRandomCars();
System.out.println("Initial Cars list: " + cars.toString());
List<Car> sortedCard = cars.stream() // Convert to a stream
.filter(car -> car.getModel() == Model.TOYOTA) //Take only toyota
.sorted(Comparator.comparing(Car::getYear).reversed()) //Sort by year DESC
.collect(Collectors.toList()); //Convert back to list
System.out.println("Sorted Cars list: " + sortedCard.toString());
}
static class CarFactory {
public static Car createCar() {
return new Car(generateRandomModel(), generateRandomYear());
}
protected static Model generateRandomModel() {
return Model.values()[ThreadLocalRandom.current().nextInt(0, Model.values().length)];
}
//between 2000 and 2021
protected static Year generateRandomYear() {
return Year.parse(String.valueOf(ThreadLocalRandom.current().nextInt(2000, 2022)));
}
public static List<Car> createTwentyRandomCars() {
return Stream.generate(CarFactory::createCar).limit(20).collect(Collectors.toList());
}
}
static class Car {
public Car(final Model model, final Year year) {
this.model = model;
this.year = year;
}
private final Model model;
private final Year year;
public Model getModel() {
return this.model;
}
public Year getYear() {
return this.year;
}
@Override
public String toString() {
return "Car{" +
"model=" + model +
", year=" + year +
'}';
}
}
enum Model {
TOYOTA,
FORD,
HONDA,
MAZDA,
DODGE
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment