简体   繁体   English

Java 8清单清单

[英]Java 8 List of List

I have one question regarding Java8 stream api. 我对Java8流api有一个问题。 I have one class as below 我有一个班级如下

class MyDetails(
    val fname:String,
    val lname:String,
    val myAccountList:List<Myaccount>
)

class Myaccount(
    val accID:String,
    val accType:String,
    val associateList:List<Associate>
)

class Associate(
    val associateID:String,
    val role:String
)

Now I want to get 现在我想

List of Myaccount 我的帐户清单

whose role is " owner "(Let us suppose). 谁的角色是“ 所有者 ”(让我们假设)。

For that i wrote below code but its not working 为此,我写了下面的代码,但它不起作用

myDetailsObject?.myAccountList?.stream()?.filter { account ->
            account?.associateList?.stream()?.allMatch{associate ->
                println("Value of Role ${associate.role}")
                "owner".equals(associate.role)}!!
        }?.collect(Collectors.toList())?.toList()

Output for Print statement is- Print语句的输出是-

Value of Role owner
Value of Role view
Value of Role read
Value of Role owner
Value of Role write
Value of Role write
Value of Role view

If owner is available in list why i am getting list of size zero? 如果所有者在列表中可用,为什么我会得到大小为零的列表? But above code is not working for me..Any suggestion would be appreciated. 但是上面的代码对我不起作用..任何建议将不胜感激。 Even though code syntax is in Kotlin but Java code would also be helpful. 即使代码语法在Kotlin中,但Java代码也会有所帮助。

Why not simply use kotlin for the job? 为什么不简单地使用kotlin来完成这项工作呢?

fun wanted(candidates: List<Myaccount>) =
    candidates.filter { it.associateList.any { it.role == "wanted" } }

By asking for 'allMatch', you expect all the elements to have 'owner'. 通过要求“ allMatch”,您期望所有元素都具有“所有者”。 use anyMatch() instead? 改用anyMatch()吗?

myDetailsObject?.myAccountList?.stream()?.filter { account ->
            account?.associateList?.stream()?.anyMatch{associate ->
                println("Value of Role ${associate.role}")
                "owner".equals(associate.role)}!!
        }?.collect(Collectors.toList())?.toList()

The Java code to filter the accounts objects whose all the associates are owner and collect as list is 过滤所有关联者均为所有者并作为列表收集的帐户对象的Java代码为

myAccountList.stream()
    .filter(account -> account.associateList.stream()
               .allMatch(associate -> "owner".equals(associate.role))
     .collect(Collectors.toList())

EDIT: (based on OP update) 编辑:(基于OP更新)

If you want to pick an account if at least one of the associates' role is owner, then you have to use anyMatch in place of allMatch 如果您要选择一个帐户,且至少有一个关联方的角色是所有者,则必须使用anyMatch代替allMatch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM