简体   繁体   English

使用lambda和流映射列表对象

[英]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. 什么是问道:使用lambda表达式和流对每张发票地图PartDescriptionQuantity ,排序Quantity和显示结果。

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? 但是,我如何也映射到PartDescription ,因此结果也显示在所显示数量的前面? I can't do this: 我不能这样做:

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

You don't use map . 您不使用map You sort the original Stream of Invoice s, and then print whatever properties you wish. 您对原始的Invoice Stream进行排序,然后打印所需的任何属性。

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM