私は宿題のこの部分で助けが必要です。指示は ラムダとストリームを使用して各請求書をその部品説明と数量に対応させ、 結果を数量でソートしてから結果を表示します。コレクションをJavaの2つのフィールドでマッピングする
私はほとんどのコードを持っていますが、私が混乱しているのは、部品の説明と数量によってどのようにマップするのかです。 1つのフィールドだけではなく、2つのフィールドでどのようにマッピングするのかを理解しています。ここに私のコードです。最後の部分は私が助けを必要とするところです。今、それは一部だけの説明でマッピングされたが、私はあなたが&&
と||
演算子を使用することができる部分の説明と数量
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);
}
}
これは助けになりました。私はこれを正確にはしませんでしたが、部品の説明と数量を取得したInvoiceクラスの新しいメソッドを作成するという考えが私に与えられました。ありがとう – Cake771