Java/Groovy自定义比较器和过滤器数组以只保留最小值

qkf9rpyu  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(116)

我有这个数组:

[{
    "id": 1,
    "type": "A1",
    "text": "Bla bla bla 1 - A1"        
},
{
    "id": 2,
    "type": "A1",
    "text": "Bla bla bla 2 - A1"                
},
{
    "id": 3,
    "type": "A1",
    "text": "Bla bla bla 3 - A1"        
}
,
{
    "id": 1,
    "type": "A2",
    "text": "Bla bla bla 1 - A2"            
}]

我需要删除重复的“id”,留下一个值较低的(例如A1比A2低)。因此,在上面的示例中,id=1和type=A2的记录应该被删除。
在groovy中,我创建了这个比较器:

class CustomComparator implements Comparator<Object>{

private HashMap<String, Integer> rank;

CustomComparator(){
    this.rank = new HashMap<>();
    this.rank.put("A1", 1);
    this.rank.put("A2", 2);
    this.rank.put("R5", 3);
    this.rank.put("R8", 4);
    this.rank.put("A4", 5);
}

@Override
public int compare(Object a , Object b){
   if(rank.get(a.type).intValue() < rank.get(b.type).intValue()){
       return -1;
   }
   if(rank.get(a.type).intValue() == rank.get(b.type).intValue()){
       return 0;
   }
   return 1;
}

}
我尝试使用array.removeAll{}删除重复的,但找不到正确的方法。有帮助吗?

h4cxqtbf

h4cxqtbf1#

它需要成为比较器吗?我首先想到的是groupByid,然后查找typemin()

List list = [[
                     "id"  : 1,
                     "type": "A1",
                     "text": "Bla bla bla 1 - A1"
             ],
             [
                     "id"  : 2,
                     "type": "A1",
                     "text": "Bla bla bla 2 - A1"
             ],
             [
                     "id"  : 3,
                     "type": "A1",
                     "text": "Bla bla bla 3 - A1"
             ],
             [
                     "id"  : 1,
                     "type": "A2",
                     "text": "Bla bla bla 1 - A2"
             ]]

Map rank = [A1:1, A2:2, R5:3, R8:4, A4:5]

List cleaned = list.groupBy { it.id }
        .collect { k, v -> v.min { rank[it.type] } }
vuktfyat

vuktfyat2#

直接按两个字段进行简单排序:

List list = [[
  "id"  : 1,
  "type": "A1",
  "text": "Bla bla bla 1 - A1"
],
[
  "id"  : 2,
  "type": "A1",
  "text": "Bla bla bla 2 - A1"
],
[
  "id"  : 3,
  "type": "A1",
  "text": "Bla bla bla 3 - A1"
],
[
  "id"  : 1,
  "type": "A2",
  "text": "Bla bla bla 1 - A2"
]]

def res = list.sort{ a, b -> a.id <=> b.id ?: b.type <=> a.type }.collectEntries{ [ it.id, it ] }.values()

assert res.toString() == '[[id:1, type:A1, text:Bla bla bla 1 - A1], [id:2, type:A1, text:Bla bla bla 2 - A1], [id:3, type:A1, text:Bla bla bla 3 - A1]]'

相关问题