筛选具有多个条件的列表

daw*_*wit 2 higher-order-functions java-8 kotlin

我有一个类似于此的数据结构:

[{option : {some object A},
  feature : "some string value",
  score : 0.9
 },
{option : {some object B},
  feature : "some other string value",
  score : 0.9
 },
{option : {some object C},
  feature : "some string value",
  score : 0.6
 },{option : {some object D},
  feature : "some string value",
  score : 1.0
 }]
Run Code Online (Sandbox Code Playgroud)

我想过滤具有独特功能的选项。如果功能相同,我想选一个得分最高的。对于上面的示例,预期结果将是:

[{option : {some object B},
  feature : "some other string value",
  score : 0.9
 },{option : {some object D},
  feature : "some string value",
  score : 1.0
 }]
Run Code Online (Sandbox Code Playgroud)

感谢Kotlin / Java 8中的示例实现(伪代码)。

zsm*_*b13 7

由于您没有提供起始代码,因此我将您的数据转换为Kotlin,例如:

data class Item(val feature: String, val score: Double)

val options = listOf(
        Item("some string value", 0.9),
        Item("some other string value", 0.9),
        Item("some string value", 0.6),
        Item("some string value", 1.0)
)
Run Code Online (Sandbox Code Playgroud)

从本质上讲,您需要的只是groupBy函数,其余的从那里开始非常简单:

val highestOfEachFeature = options
        .groupBy { it.feature }
        .map { it.value.maxBy { it.score } }
Run Code Online (Sandbox Code Playgroud)

结果如下:

[Option(feature=some string value, score=1.0), Option(feature=some other string value, score=0.9)]
Run Code Online (Sandbox Code Playgroud)