Java 以对象作为键,以整数作为值对Hashmap进行排序
我有一个Hashmap,其中包含一个对象Customer作为键和一个整数“number of products”作为值 我想从这个hashmap中获得产品数量最少的customer对象 通过使用流,我尝试了两种方法,但似乎总是得到一个随机对象,而不是int值最低的对象 有人能帮忙吗Java 以对象作为键,以整数作为值对Hashmap进行排序,java,sorting,hashmap,Java,Sorting,Hashmap,我有一个Hashmap,其中包含一个对象Customer作为键和一个整数“number of products”作为值 我想从这个hashmap中获得产品数量最少的customer对象 通过使用流,我尝试了两种方法,但似乎总是得到一个随机对象,而不是int值最低的对象 有人能帮忙吗 Map<Customer, Integer> customerMap = new HashMap<>(); for (Customer customer:customers) {
Map<Customer, Integer> customerMap = new HashMap<>();
for (Customer customer:customers) {
customerMap.put(customer, customer.getProducts().size());
}
customerMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.naturalOrder()))
.findFirst().get().getKey()
customerMap.entrySet().stream()
.min(Map.Entry.comparingByValue(Integer::compareTo))
.get().getKey()
Map customerMap=newhashmap();
用于(客户:客户){
customerMap.put(customer,customer.getProducts().size());
}
customerMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.naturalOrder()))
.findFirst().get().getKey()
customerMap.entrySet().stream()
.min(Map.Entry.comparingByValue(Integer::compareTo))
.get().getKey()
我看不出你的问题,当我测试你的代码时,它会返回正确的客户
不使用Map
获得结果的其他两种方法是:
1-根据其产品
列表大小对客户列表进行排序,并取第一个:(如Maia所述)
2-对循环使用经典的:
Customer c = customers.get(0);
for(Customer cu : customers) {
if(cu.getProducts().size() < c.getProducts().size())
c = cu;
}
Customer c=customers.get(0);
对于(客户cu:客户){
if(cu.getProducts().size()
如果您只想找到具有最小值的键,就不必对集合进行排序
如果确定只有一个值最小的键(可能有更多),则可以执行以下操作:
Customer customerWithSmallestValue = map.entrySet().stream()
.min(Comparator.comparingInt(Map.Entry::getValue))
.map(Map.Entry::getKey)
.get();
或者
Customer customerWithSmallestValue = map.entrySet().stream()
.min(Map.Entry.comparingByValue(Integer::compareTo))
.map(Map.Entry::getKey)
.get();
请注意,如果地图中有多个键具有最小值,这两个选项将为您提供上次找到的结果
“使用lambda表达式”您没有使用任何lambda表达式。您正在使用Streams和方法引用。是的,但我想用lambda表达式解决这个问题,但我不知道如何解决。因此,第1步是了解lambda表达式是什么,然后实际编写一个。@wind99t当我测试代码时,它返回两个流表达式的正确客户。这个问题与排序有什么关系?您只想得到最小的值,而不需要排序。作为一个侧节点,HashMap不是一个有序的集合,所以我们不能真正讨论如何对它进行排序。
Customer customerWithSmallestValue = map.entrySet().stream()
.min(Map.Entry.comparingByValue(Integer::compareTo))
.map(Map.Entry::getKey)
.get();