首先,我有以下发票列表。每个列表对象都有一个零件号,描述,数量和价格。
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);
问的是:使用lambdas和stream映射PartDescription
和Quantity
上的每张发票,按Quantity
排序并显示结果。
所以我现在拥有的:
list.stream()
.map(Invoice::getQuantity)
.sorted()
.forEach(System.out::println);
我以数量映射并以数量进行排序,我的结果低于:
:3
7
11
16
18
21
34
76
但是我也如何在PartDescription
上映射,因此在显示数量的前面我的结果中也显示了这一点?我不能这样做:
list.stream()
.map(Invoice::getPartDescription)
.map(Invoice::getQuantity)
.sorted()
.forEach(System.out::println);
您不使用map
。您对Invoice
S的原始Stream
进行排序,然后打印您想要的任何属性。
list.stream()
.sorted(Comparator.comparing(Invoice::getQuantity))
.forEach(i -> System.out.println(i.getgetQuantity() + " " + i.getPartDescription()));
编辑:如果要按数量进行排序 *价格:
list.stream()
.sorted(Comparator.comparing(i -> i.getQuantity() * i.getPrice()))
.forEach(i -> System.out.println(i.getgetQuantity() * i.getPrice() + " " + i.getPartDescription()));