![](/img/trans.png)
[英]Java8 Stream List<Map<String,Object>> groupingBy and counting value
[英]Using Java8 stream(), collect(), and groupingBy() , etc to add integer value based on two same beans properties value
我有一個豆子:
class Foo {
private String category;
private int qty;
private int price;
}
現在我有一個清單:
List foos = new ArrayList();
foos.add(new Foo("A", 1, 10));
foos.add(new Foo("A", 2, 10));
foos.add(new Foo("A", 2, 20));
foos.add(new Foo("B", 1, 10));
foos.add(new Foo("C", 1, 30));
foos.add(new Foo("C", 5, 10));
我想添加類別和數量相同的價格,例如兩個相同的A類別有兩個相同的數量(Foo("A", 2, 10), new Foo("A", 2, 20)),然后是另一個或相同的列表應為“A 1 10”和“A 2 30”
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Main {
private static <T> Predicate<T> distinctByKeys(Function<? super T, ?>... keyExtractors) {
final Map<List<?>, Boolean> seen = new ConcurrentHashMap<>();
return t -> {
final List<?> keys = Arrays.stream(keyExtractors).map(ke -> ke.apply(t)).collect(Collectors.toList());
return seen.putIfAbsent(keys, Boolean.TRUE) == null;
};
}
public static void main(String[] args) {
List<Foo> foos = new ArrayList<>();
List<Foo> resultfoos = new ArrayList<>();
foos.add(new Foo("A", 1, 10));
foos.add(new Foo("A", 2, 10));
foos.add(new Foo("A", 2, 20));
foos.add(new Foo("B", 1, 10));
foos.add(new Foo("C", 1, 30));
foos.add(new Foo("C", 5, 10));
foos.stream().filter(distinctByKeys(Foo::getCategory, Foo::getQty)).forEach(o -> {
o.setPrice(foos.stream().distinct()
.filter(x -> x.getCategory().equalsIgnoreCase(o.getCategory()) && x.getQty() == o.getQty())
.mapToInt(t -> t.getPrice()).sum());
System.out.println(o.toString());
resultfoos.add(o), o.getPrice()));
});
}
}
class Foo {
private String category;
private int qty;
private int price;
Foo(String category, int qty, int price) {
this.category = category;
this.qty = qty;
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Foo [category=" + category + ", qty=" + qty + ", price=" + price + "]";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.