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

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

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&lt;String&gt; names;
}

class Test {
  private List&lt;Obj&gt; 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&lt;? super Obj&gt; predicate) method.

  public boolean isPresent() {
	  return objs.stream().anyMatch( o -&gt; o.getNames().size() &gt; 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&lt;? super Obj&gt; predicate) method

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

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:

确定