通过java中的两个字段映射集合

时间:2016-03-27 18:18:20

标签: java

我只需要帮助完成这部分作业。说明是 使用lambda和流将每个Invoice映射到PartDescription和Quantity, 按数量对结果进行排序,然后显示结果。

我有大部分代码,但我感到困惑的是如何按部件描述和数量进行映射。我理解如何只用一个字段而不是两个字段进行映射。这是我的代码。最后一部分是我开始需要帮助的地方。现在它只是按部件描述映射,但我需要按部件描述和数量进行映射

import java.util.*;
import java.util.function.Function;

public class ProcessInvoices {

    public static void main(String[] args) {

        //initialize array of invoice objects
        Invoice[] invoices = {
                new Invoice(83 , "Electric sander", 7 , 57.89),
                new Invoice(24, "Power saw", 18, 99.99),
                new Invoice(7, "Sledge hammer", 11, 21.50),
                new Invoice(77, "Hammer", 76, 11.99),
                new Invoice(39, "Lawn mower", 3, 79.50),
                new Invoice(68, "Screwdriver" ,106, 6.99),
                new Invoice(56, "Jig saw", 21 ,11.00),
                new Invoice(3, "Wrench" ,34, 7.50)};

        List<Invoice> list = Arrays.asList(invoices);
        System.out.println("List of Invoice items: ");
        list    .stream()
                .forEach(System.out::println);

        //Fucnction for getting part information for sorting
        Function<Invoice, String> byPartDescription = Invoice::getPartDescription;
        Function<Invoice, Double> byPrice = Invoice::getPrice;
        Function<Invoice, Integer> byQuantity = Invoice::getQuantity:;

        //Comparator for invoice objects by part descsriprion
        Comparator<Invoice> justPartDesc =
                Comparator.comparing(byPartDescription);

        //sort by part description
        System.out.printf("%nInvoice objects in ascending order by part description: %n");
        list    .stream()
                .sorted(justPartDesc)
                .forEach(System.out::println);

        //Comparator for invoice by price
        Comparator<Invoice> justPrice = Comparator.comparing(byPrice);
        //sort by price
        System.out.printf("%nInvoice Obejects sorted in ascending order by price: %n");
        list    .stream()
                .sorted(justPrice)
                .forEach(System.out::println);

        Comparator<Invoice> justQuantity = Comparator.comparing(byQuantity);

        //map invoice to part descripiton and quantity
        System.out.printf("%nInvoice objects mapped to part descripton and Quantity");
        list    .stream()
                .map(Invoice::getPartDescription)
                .distinct()
                .sorted()
                .forEach(System.out::println);

    }
}

2 个答案:

答案 0 :(得分:0)

  

使用lambdas和流将每个发票映射到其PartDescription和Quantity

如果说明明确说明从发票映射到PartDescription和Quantity,您可以创建一个表示PartDescription和Quantity的类,并从Invoice映射到新类.setLayout(null)的实例。

PartDescriptionAndQuantity

另一方面,如果说明只是希望您显示描述和数量(并从发票中获取描述和数量便宜),那么您可以按数量对发票进行排序,然后只打印描述和数量。

答案 1 :(得分:-1)

您可以使用&&||运算符。您需要更改最后一个map参数的逻辑,并使用逻辑运算符传递它们。