0

I'm trying to order the list below of workers by the quantity of this days . But I can't get the right way to do that. I can order them by ID for example on this way:

workers.stream().sorted(Comparator.comparingInt(Worker::getId)).collect(Collectors.toList());

But I can't find the way to use the Worker.getDays().size() to order them....

    "workers": [
        {
          "id": 1,
          "days": ["Monday", "Wednesday", "Friday"]
        },
        {
          "id": 2,
          "days": ["Tuesday", "Thursday"]
        },
        {
          "id": 3,
          "days": ["Monday", "Tuesday", "Friday"]
        },
        {
          "id": 4,
          "days": ["Thursday"]
        },   
]

Hope I could find a nice solution, thanks in advance :)

1

3 Answers 3

3

Just use a lambda-expression to get the days of a worker and the size..

  List<Worker> workersSortedByDaysSize = workers.stream()
    .sorted(Comparator.comparingInt(w -> w.getDays().size()))
    .collect(Collectors.toList());

This assumes days is not null.

Sign up to request clarification or add additional context in comments.

2 Comments

It works perfectly, I didn't how to build the lambda, thanks a lot
You're welcome. I hope the linked documentation will help you to understand how to write lambda-expressions.
0

Try:

List<Worker> sorted = workers
    .stream()
    .sorted(Comparator.comparingInt(w -> w.getDays().size()))
    .collect(Collectors.toList());

Comments

0

workers.stream().sorted((w1, w2) -> w1.getDays().size() - w2.getDays().size()).collect(Collectors.toList());
or do w2-w1 to reverse the list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.