How do I return a boolean if a value is present in a list inside a list using java 8

huangapple go评论90阅读模式
英文:

How do I return a boolean if a value is present in a list inside a list using java 8

问题

  1. import java.util.List;
  2. import java.util.Objects;
  3. class Obj {
  4. private List<String> names;
  5. public List<String> getNames() {
  6. return names;
  7. }
  8. }
  9. class Test {
  10. private List<Obj> objs;
  11. public boolean isPresent(String name) {
  12. return objs.stream()
  13. .map(Obj::getNames)
  14. .filter(Objects::nonNull)
  15. .anyMatch(names -> names.size() > 1);
  16. }
  17. }
英文:

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

  1. class Obj {
  2. private List&lt;String&gt; names;
  3. }
  4. class Test {
  5. private List&lt;Obj&gt; objs;
  6. public boolean isPresent(String name) {
  7. //Loop through the list of lists
  8. }
  9. }

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) 方法。

  1. public boolean isPresent() {
  2. return objs.stream().anyMatch(o -> o.getNames().size() > 1);
  3. }

如果你希望仅在所有节点的 names 列表长度都大于1(因此不为 null)的情况下返回 true,你可以使用 boolean java.util.stream.Stream.allMatch(Predicate<? super Obj> predicate) 方法。

  1. public boolean isPresent() {
  2. return objs.stream().allMatch(o -> o.getNames().size() > 1);
  3. }
英文:

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&lt;? super Obj&gt; predicate) method.

  1. public boolean isPresent() {
  2. return objs.stream().anyMatch( o -&gt; o.getNames().size() &gt; 1 );
  3. }

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&lt;? super Obj&gt; predicate) method

  1. public boolean isPresent() {
  2. return objs.stream().allMatch( o -&gt; o.getNames().size() &gt; 1 );
  3. }

huangapple
  • 本文由 发表于 2020年8月28日 22:48:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63636113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定