问题描述
我有方法 returnSpecificOrder(Type type)(就像下面的代码一样),其中 Type 是 enum class ,这个方法应该只返回包含 item.type = "Clothes" 的 Orders,其中 Item 是另一个具有变量 public Type type 的类;我尝试从 hashMap 返回订单,但 java 说无法解析符号,我应该如何更改我的方法?
public class Order {
public long id;
public LocalDate dateTime;
public User user;
public List<Item> items;
//set seters and geters
public HashMap<Long,Order> createOrder() {
Order myFirstOrder = new Order();
myFirstOrder.setId(1);
myFirstOrder.setDateTime(LocalDate.Now());
myFirstOrder.setUser(user);
myFirstOrder.setItems(items);
Order mySecondOrder = new Order();
mySecondOrder.setId(2);
mySecondOrder.setDateTime(LocalDate.Now());
mySecondOrder.setUser(user);
mySecondOrder.setItems(item2);
//hash map of orders
HashMap<Long,Order> orders = new HashMap<>();
orders.put(myFirstOrder.getId(),myFirstOrder);
orders.put(mySecondOrder.getId(),mySecondOrder);
return orders;
}
//method that will return only Orders containing item.type = "Clothes"
public static Map<Long,Order> returnSpecificOrder(Type type) {
return orders.entrySet()
.stream()
.filter(o -> o.getValue().getItems().stream().anyMatch(item -> item.getType() == Type.clothes))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
} }
解决方法
您的过滤器应该可以工作。
以下是工作代码。
我重构了您的实体类,并在需要的地方添加了注释。
class Order {
public long id;
public List<Item> items;
//convenient constructor.
public Order(long id,Type... items) {
this.id = id;
this.items = Arrays.stream(items).map(Item::new).collect(Collectors.toList());
}
}
class Item {
Type type;
public Item(Type type) {
this.type = type;
}
}
enum Type {
Clothes,NotClothes,Car,Bicycle,Shoes
}
然后将您的过滤器方法添加到 main
public class Main {
public static void main(String[] args) {
//pre-populate with sample data
Order o1 = new Order(1,Type.Bicycle,Type.Car,Type.Clothes);
Order o2 = new Order(2,Type.NotClothes,Type.Bicycle);
HashMap<Long,Order> orders = new HashMap<>();
orders.put(1L,o1);
orders.put(2L,o2);
//method that will return only Orders containing item.type = "Clothes"
Map<Long,Order> result = orders.entrySet().stream()
.filter(o -> {
//I Split into two lines to make it less cluttered.
List<Item> list = o.getValue().items;
return list.stream().anyMatch(item -> item.type == Type.Clothes);
}).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
//The answer shows that only 1 item is returned.
System.out.println("result = " + result.size());
}
}