Filter Java Stream to 1 and only 1 element(将 Java Stream 过滤为 1 个且仅 1 个元素)
问题描述
我正在尝试使用 Java 8 Stream
s 在 LinkedList
中查找元素.但是,我想保证只有一个匹配过滤条件.
I am trying to use Java 8 Stream
s to find elements in a LinkedList
. I want to guarantee, however, that there is one and only one match to the filter criteria.
获取此代码:
public static void main(String[] args) {
LinkedList<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
User match = users.stream().filter((user) -> user.getId() == 1).findAny().get();
System.out.println(match.toString());
}
<小时>
static class User {
@Override
public String toString() {
return id + " - " + username;
}
int id;
String username;
public User() {
}
public User(int id, String username) {
this.id = id;
this.username = username;
}
public void setUsername(String username) {
this.username = username;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public int getId() {
return id;
}
}
此代码根据他们的 ID 找到 User
.但无法保证有多少 User
匹配过滤器.
This code finds a User
based on their ID. But there are no guarantees how many User
s matched the filter.
将过滤器行更改为:
User match = users.stream().filter((user) -> user.getId() < 0).findAny().get();
会抛出 NoSuchElementException
(好!)
不过,如果有多个匹配项,我希望它抛出错误.有没有办法做到这一点?
I would like it to throw an error if there are multiple matches, though. Is there a way to do this?
推荐答案
创建自定义 收集器
public static <T> Collector<T, ?, T> toSingleton() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.size() != 1) {
throw new IllegalStateException();
}
return list.get(0);
}
);
}
我们使用 Collectors.collectingAndThen
来构造我们想要的Collector
by
- 使用
Collectors.toList()
收集器在List
中收集我们的对象. - 在最后应用一个额外的完成器,返回单个元素 - 如果
list.size != 1
则抛出IllegalStateException
.
- Collecting our objects in a
List
with theCollectors.toList()
collector. - Applying an extra finisher at the end, that returns the single element — or throws an
IllegalStateException
iflist.size != 1
.
用作:
User resultUser = users.stream()
.filter(user -> user.getId() > 0)
.collect(toSingleton());
然后,您可以根据需要自定义此 Collector
,例如将异常作为构造函数中的参数,调整它以允许两个值等等.
You can then customize this Collector
as much as you want, for example give the exception as argument in the constructor, tweak it to allow two values, and more.
您可以使用涉及 peek()
和 AtomicInteger
的解决方法",但实际上您不应该使用它.
You can use a 'workaround' that involves peek()
and an AtomicInteger
, but really you shouldn't be using that.
你可以做的只是把它收集到一个List
中,像这样:
What you could do istead is just collecting it in a List
, like this:
LinkedList<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
List<User> resultUserList = users.stream()
.filter(user -> user.getId() == 1)
.collect(Collectors.toList());
if (resultUserList.size() != 1) {
throw new IllegalStateException();
}
User resultUser = resultUserList.get(0);
这篇关于将 Java Stream 过滤为 1 个且仅 1 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 Java Stream 过滤为 1 个且仅 1 个元素
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01