英文:
How do I return a boolean if a value is present in a list inside a list using java 8
问题
import java.util.List;
import java.util.Objects;
class Obj {
private List<String> names;
public List<String> getNames() {
return names;
}
}
class Test {
private List<Obj> objs;
public boolean isPresent(String name) {
return objs.stream()
.map(Obj::getNames)
.filter(Objects::nonNull)
.anyMatch(names -> names.size() > 1);
}
}
英文:
I have a List of objects, which contains a list of Strings. I want to return true if the 'names' list is not null and has size more than 1.
Consider the below code
class Obj {
private List<String> names;
}
class Test {
private List<Obj> objs;
public boolean isPresent(String name) {
//Loop through the list of lists
}
}
Here I want to determine if 'names' is not null and has size more than 1 for any of the 'objs' objects. Is there a way we can do this using Streams in java 8?
答案1
得分: 3
Preface
你的要求有点不太清楚。你的要求可以理解为两种情况:
- 如果任何一个 names 数组的长度大于1,则返回 true,或者
- 如果所有 names 数组的长度都大于1,则返回 true
请记住,objs 列表中的每个节点都有一个 names 数组。
Code
如果你希望在任何一个 names 列表中的节点长度大于1时返回 true,你可以使用 boolean java.util.stream.Stream.anyMatch(Predicate<? super Obj> predicate)
方法。
public boolean isPresent() {
return objs.stream().anyMatch(o -> o.getNames().size() > 1);
}
如果你希望仅在所有节点的 names 列表长度都大于1(因此不为 null)的情况下返回 true,你可以使用 boolean java.util.stream.Stream.allMatch(Predicate<? super Obj> predicate)
方法。
public boolean isPresent() {
return objs.stream().allMatch(o -> o.getNames().size() > 1);
}
英文:
Preface
Your requirements are a bit unclear. You're requirements could be read both as
- Return true if any names array has greater than 1, or
- Return true if all the names arrays are greater than 1
> Remember, there is a names array for each node in the objs list.
Code
If you want to return true if any node in the names lists are greater than 1 then you would use the boolean java.util.stream.Stream.anyMatch(Predicate<? super Obj> predicate)
method.
public boolean isPresent() {
return objs.stream().anyMatch( o -> o.getNames().size() > 1 );
}
If you want to return true only in the case where all the nodes are greater than 1, and therefore not null, you would use the boolean java.util.stream.Stream.allMatch(Predicate<? super Obj> predicate)
method
public boolean isPresent() {
return objs.stream().allMatch( o -> o.getNames().size() > 1 );
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论