// 总体要实现:找到每个人交易额总的和最小的那个人的信息
public void lambdaPractice() {
Trader raoul = new Trader("Raoul", "Cambridge");
Trader mario = new Trader("Mario", "Milan");
Trader alan = new Trader("Alan", "Cambridge");
Trader brian = new Trader("Brian", "Cambridge");
// 这里是个知识点你需要将Arrays.asList方式转化成ArrayList这种方式
// 否则在使用transactions.remove()方法时会报UnsupportedOperationException
List<Transaction> transactions = new ArrayList<>(Arrays.asList(new Transaction(brian, 2011, 300),
new Transaction(raoul, 2012, 1000), new Transaction(raoul, 2011, 400),
new Transaction(mario, 2012, 710), new Transaction(mario, 2012, 700), new Transaction(alan, 2012, 950)));
// 将同一个人的交易额进行加算生成新的集合
List<Transaction> sumList = new ArrayList<>();
for (int i = 0; i < transactions.size(); i++) {
for (int j = i + 1; j < transactions.size(); j++) {
if (transactions.get(i).getTrader().getName().equals(transactions.get(j).getTrader().getName())) {
Trader t = new Trader();
t.setCity(transactions.get(i).getTrader().getCity());
t.setName(transactions.get(i).getTrader().getName());
Transaction temp = new Transaction();
temp.setYear(transactions.get(i).getYear());
int sum = transactions.get(i).getValue() + transactions.get(j).getValue();
temp.setValue(sum);
temp.setTrader(t);
sumList.add(temp);
}
}
}
// 在原始集合中删除已加算完成的人的信息
for (int i = 0; i < transactions.size(); i++) {
for (int j = 0; j < sumList.size(); j++) {
if (transactions.get(i).getTrader().getName().equals(sumList.get(j).getTrader().getName())) {
// 这里也是注意点
// 删除时索引会发生变化,我们可以使索引同步
transactions.remove(i--);
}
}
}
// 再将加算完成的人的信息加入到原始List中
for (Transaction transaction : sumList) {
transactions.add(transaction);
}
// 找到每个人交易额总和最小的那个人的信息
Transaction transaction = transactions.stream().min((x, y) -> x.getValue() - y.getValue()).get();
}