我正在努力减少一个列表:
假设我有一个定义了Item
类的List<Item> listItems
,如下所示:
public class Item {
private String effect;
private String value;
public String getEffect() {
return effect;
}
public void setEffect(String effect) {
this.effect = effect;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
现在,在我的listItems
列表中,我有一些具有相同effect
属性的元素。
我想从我的listItems
列表中删除具有相同effect
属性的所有元素,但具有更高value
属性的元素除外。(value
是用String
表示的数字)。
另外,我希望所有的元素都有一个唯一的effect
属性。
我怎样才能做到这一点呢?我想我得和Comparator
打交道了。
发布于 2018-10-19 18:07:13
“我希望所有元素都有一个唯一的effect属性”:假设所有的Item
对象都有有效的effect
和value
:
//group list entries to sub - lists having the same effect value
Map<String, List<Item>> map = itemList.stream()
.collect(Collectors.groupingBy(Item::getEffect)) ;
List<Item> uniqueEfectMaxValue = new ArrayList<>();
//get item having max value and add to uniqueEfectMaxValue
map.forEach((key,list)->{
Item item = list.stream().
collect(Collectors.maxBy(Comparator.
comparing(Item::getValue))).get();
uniqueEfectMaxValue.add(item);
}
);
https://stackoverflow.com/questions/52879473
复制相似问题