在下面的示例中,我想打印出被丢弃的物品的 ID。有没有办法不仅获取值,还获取对象本身?
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Example list with potential duplicates
List<Item> items = Arrays.asList(
new Item(1, "Item A"),
new Item(2, "Item B"),
new Item(1, "Item C"), // Duplicate key
new Item(3, "Item D")
);
// Building the Map
Map<Integer, String> itemMap = items.stream()
.collect(Collectors.toMap(
Item::getId, // Key mapper
Item::getName, // Value mapper
(existing, incoming) -> { // Merge function
// Print info about the duplicate
System.out.println("Duplicate key found. Existing value: " + existing + ", Incoming value: " + incoming);
// HOW CAN I PRINT THE INCOMING ELEMENTS ID HERE? <<<<<<<<<<<<
return incoming; // Keep the incoming value
}
));
// Print the resulting map
System.out.println("Resulting Map: " + itemMap);
}
}
class Item {
private final int id;
private final String name;
public Item(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Item{id=" + id + ", name='" + name + "'}";
}
}
您可以使用
Map<Integer, String> itemMap = items.stream()
.collect(Collectors.groupingBy(
Item::getId, // Key mapper
Collectors.collectingAndThen(
Collectors.reducing((existing, incoming) -> { // Merge function
// Print info about the duplicate
System.out.println("Duplicate key " + existing.getId()
+ " found. Existing value: " + existing.getName()
+ ", Incoming value: " + incoming.getName());
return incoming; // Keep the incoming value
}), o -> o.get().getName() // Value mapper
)));
Duplicate key 1 found. Existing value: Item A, Incoming value: Item C
Resulting Map: {1=Item C, 2=Item B, 3=Item D}
但您也可以考虑传统循环:
Map<Integer, String> itemMap = new HashMap<>();
for(Item i: items) {
String old = itemMap.put(i.getId(), i.getName());
if(old != null) {
System.out.println("Duplicate key " + i.getId()
+ " found. Existing value: " + old + ", Incoming value: " + i.getName());
}
}