DrAhzek
DrAhzek

Reputation: 195

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

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

Upvotes: 2

Views: 170

Answers (4)

listPersonVO.stream().sorted((o1, o2)->o1.getName().trim().compareTo(o2.getName().trim())).collect(Collectors.toList());

enter image description here

Upvotes: 1

azro
azro

Reputation: 54168

As the other answer tells you, you need to add the .sorted() operation in the stream


Next to that I'd like to suggest you a different way for comparing your Person:

static Comparator<Person> comparator = 
        Comparator.comparing(Person::getName, String.CASE_INSENSITIVE_ORDER)
                  .thenComparing(Person::getColour)
                  .thenComparing(Person::getAge);

@Override
public int compareTo(Person person) {
    return comparator.compare(this, person);
}

// with the different getters

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56473

As your Person objects are Comparable, you can directly call the sorted method and print the result.

people.stream()
      .sorted()
      .forEachOrdered(n->System.out.println(n.getName() + " " + n.getColour()));

note that I've used forEachOrdered as opposed to forEach to guarantee the elements are printed in the sorted order.


You may also decide to sort my name only or by colour only without changing your current compareTo implementation, in which case you can use a custom comparator:

people.stream()
      .sorted(Comparator.comparing(Person::getName, String.CASE_INSENSITIVE_ORDER))
      .forEachOrdered(n->System.out.println(n.getName() + " " + n.getColour()));

and by colour:

people.stream()
      .sorted(Comparator.comparing(Person::getColour, String.CASE_INSENSITIVE_ORDER))
      .forEachOrdered(n->System.out.println(n.getName() + " " + n.getColour()));

Upvotes: 5

Naman
Naman

Reputation: 32028

You can sort it using Stream.sorted as:

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

Upvotes: 5

Related Questions