我有一个列表a,我想分成几个小列表.
说出包含"aaa"的所有项目,包含"bbb"和更多谓词的所有内容.
我怎么能用java8这样做?
我看到这篇文章,但它只分成两个列表.
public void partition_list_java8() {
Predicate<String> startWithS = p -> p.toLowerCase().startsWith("s");
Map<Boolean, List<String>> decisionsByS = playerDecisions.stream()
.collect(Collectors.partitioningBy(startWithS));
logger.info(decisionsByS);
assertTrue(decisionsByS.get(Boolean.TRUE).size() == 3);
}
Run Code Online (Sandbox Code Playgroud)
我看过这篇文章,但它在Java 8之前很老了.
我有一个流,其中每个对象都由唯一的 id 标识。此外,每个对象都有正值或负值Free。
我想将此流分为两个集合,其中一个包含值为ids正Free的值,另一个包含其余值。
但我发现以下方法不是正确的方法,因为我正在将数据收集到流之外的列表中。
class Foo {
int free;
long id;
}
public Tuple2<Set<Long>, Set<Long>> findPositiveAndNegativeIds() {
Set<Long> positives = new HashSet<>();
Set<Long> negatives = new HashSet<>();
foos.stream()
.forEach(f -> {
if (f.free >= 0) positigves.add(f.id);
else negatives.add(f.id);
});
return Tuple2.tuple(positives, negatives);
}
Run Code Online (Sandbox Code Playgroud)
partitionBy()可以通过某种方式或类似方式做得更好吗?
我需要检查类的Id变量是否为null。如果为null,则必须将其插入一个列表中;如果不为null,则必须将其插入另一列表中。我这样做是这样的:
我不希望有两个流,我只想做一个,然后使用Strem和过滤器,您能帮我吗?
具有空ID的电子邮件将保留在数据库中。
List<Email> emails = payment.getUser().getEmails();
if (!emails.isEmpty()){
List<Email> create = emails.stream().filter(email -> email.getId() == null).collect(Collectors.toList());
List<Email> existingEmails = emails.stream().filter(email -> email.getId() != null).collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)