Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Finding the Top 3 Hardest-Working Employees | Intermediate Operations in Stream API
Stream API

book
Challenge: Finding the Top 3 Hardest-Working Employees

Tarea

Swipe to start coding

Several employees work at the factory, and we need to identify the three hardest-working employees based on the number of hours worked.

  1. Sort the list of workers in ascending order by the number of hoursWorked using the comparingInt() method.
  2. Reverse the list of workers to make it descending by the number of hoursWorked using the reversed() method.
  3. Select the top three workers with the highest hoursWorked using the limit() method.
  4. Print each of these three workers to the console.

Solución

java

solution

package com.example;

import java.util.List;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
List<Worker> workers = List.of(
new Worker("John", 160),
new Worker("Michael", 200),
new Worker("Andrew", 180),
new Worker("David", 220),
new Worker("Robert", 175)
);

List<Worker> topWorkers = workers.stream()
.sorted(Comparator.comparingInt(Worker::getHoursWorked).reversed())
.limit(3)
.toList();

topWorkers.forEach(System.out::println);
}
}

class Worker {
private String name;
private int hoursWorked;

public Worker(String name, int hoursWorked) {
this.name = name;
this.hoursWorked = hoursWorked;
}

public String getName() {
return name;
}
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 10
package com.example;

import java.util.List;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
List<Worker> workers = List.of(
new Worker("John", 160),
new Worker("Michael", 200),
new Worker("Andrew", 180),
new Worker("David", 220),
new Worker("Robert", 175)
);

List<Worker> topWorkers = workers.stream()
.sorted(Comparator.comparingInt(___).___)
.___
.toList();

topWorkers.forEach(___);
}
}

class Worker {
private String name;
private int hoursWorked;

public Worker(String name, int hoursWorked) {
this.name = name;
this.hoursWorked = hoursWorked;
}

public String getName() {
return name;
}

public int getHoursWorked() {
return hoursWorked;
}

@Override
public String toString() {
return "Worker{name='" + name + "', hoursWorked=" + hoursWorked + "}";
}
}
toggle bottom row
We use cookies to make your experience better!
some-alt