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

book
Challenge: Finding the Top 3 Hardest-Working Employees

Tehtävä

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.

Ratkaisu

solution.java

solution.java

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;
}
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 10
single

single

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;
}

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

We use cookies to make your experience better!
some-alt