Sorting values of an arraylist objects and printing multiple of them in one lambda

DrAhzek :

My goal is to print out two values out of four - name (string) and hair colour (enum) - that describe a certain object in an arraylist. The problem lies with sorting the printed list alphabetically by name. It all has to be in one lambda.

I'm stuck with just printing it out, without sorting. I've already set up the overrides but since I'm still learning, I can't seem to get it work.

public void printAllNamesColours() {
        people.stream()
            .forEach(n->System.out.println(n.getName() + " " + n.getColour()));
    }

@Override
public int compareTo(Person person) {
        int ret = name.compareToIgnoreCase(person.name);
        if (ret == 0) {
            ret = colour.compareTo(person.colour);
        }
        if (ret == 0) {
            ret = age - person.age;
        }
        return ret;
    }
Naman :

You can sort it using Stream.sorted as:

people.stream()
      .sorted() // considering your `compareTo` implementation
      .forEach(n -> System.out.println(n.getName() + " " + n.getColour()));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111074&siteId=1