Sitjuh
Sitjuh

Reputation: 117

Mapping List objects using lambdas and streams

To start with, I have the following list of invoices. Each list object has a part number, a description, quantity and a price.

Invoice[] invoices = new Invoice[8];
invoices[0] = new Invoice("83","Electrische schuurmachine",7,57.98);
invoices[1] = new Invoice("24","Power zaag", 18, 99.99);
invoices[2] = new Invoice("7","Voor Hamer", 11, 21.50);
invoices[3] = new Invoice("77","Hamer", 76, 11.99);
invoices[4] = new Invoice("39","Gras maaier", 3, 79.50);
invoices[5] = new Invoice("68","Schroevendraaier", 16, 6.99);
invoices[6] = new Invoice("56","Decoupeer zaal", 21, 11.00);
invoices[7] = new Invoice("3","Moersleutel", 34, 7.50);

List<Invoice> list = Arrays.asList(invoices);

What's asked: Use lambdas and streams to map every Invoice on PartDescription and Quantity, sort by Quantity and show the results.

So what I do have now:

list.stream()
    .map(Invoice::getQuantity)
    .sorted()
    .forEach(System.out::println);

I mapped it on quantity and sorted it on quantity as well and I get below results:

3
7
11
16
18
21
34
76

But how do I map on PartDescription as well, so that's showed in my results in front of the shown quantities too? I can't do this:

list.stream()
    .map(Invoice::getPartDescription)
    .map(Invoice::getQuantity)
    .sorted()
    .forEach(System.out::println);

Upvotes: 1

Views: 172

Answers (1)

Eran
Eran

Reputation: 394126

You don't use map. You sort the original Stream of Invoices, and then print whatever properties you wish.

list.stream()
    .sorted(Comparator.comparing(Invoice::getQuantity))
    .forEach(i -> System.out.println(i.getgetQuantity() + " " + i.getPartDescription()));

EDIT: If you want to sort by quantity * price:

list.stream()
    .sorted(Comparator.comparing(i -> i.getQuantity() * i.getPrice()))
    .forEach(i -> System.out.println(i.getgetQuantity() *  i.getPrice() + " " + i.getPartDescription()));

Upvotes: 4

Related Questions