将 Java Stream 过滤为 1 个且仅 1 个元素

Filter Java Stream to 1 and only 1 element(将 Java Stream 过滤为 1 个且仅 1 个元素)

本文介绍了将 Java Stream 过滤为 1 个且仅 1 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java 8 Streams 在 LinkedList 中查找元素.但是,我想保证只有一个匹配过滤条件.

I am trying to use Java 8 Streams 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 Users 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

  1. 使用 Collectors.toList() 收集器在 List 中收集我们的对象.
  2. 在最后应用一个额外的完成器,返回单个元素 - 如果 list.size != 1 则抛出 IllegalStateException.
  1. Collecting our objects in a List with the Collectors.toList() collector.
  2. Applying an extra finisher at the end, that returns the single element — or throws an IllegalStateException if list.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 个元素

基础教程推荐