如何选择集合中最大的元素之一 [英] How to choose one of the largest elements in a collection

查看:126
本文介绍了如何选择集合中最大的元素之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组列表,我想找到具有最大 x 值的元组。在有多个最大 x 值的情况下,我想随机选择一个。我无法弄清楚如何实现这种随机选择功能。下面是我到目前为止的代码:

I have a list of tuples, and I want to find the tuples with the largest x value. In the case where there are multiple largest x values, I want to choose one at random. I can't figure out how to implement this random selection functionality. Below is the code I have so far:

public void testSelectRandomFromLargestVals() {
    List<Tuple<Integer, String>> list = new ArrayList<>();
    list.add(new Tuple<>(5, "five-1"));
    list.add(new Tuple<>(2, "two"));
    list.add(new Tuple<>(3, "three"));
    list.add(new Tuple<>(5, "five-2"));
    list.add(new Tuple<>(5, "five-3"));

    Optional<Tuple<Integer, String>> largestTuple = list.stream().max((t1, t2) -> Integer.compare(t1.x, t2.x));
    System.out.println("Largest tuple is: " + largestTuple.get().x + " value is: " + largestTuple.get().y);
}

public class Tuple<X, Y> {
    public final X x;
    public final Y y;
    public Tuple(X x, Y y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Tuple<?, ?> tuple = (Tuple<?, ?>) o;
        if (!x.equals(tuple.x)) return false;
        return y.equals(tuple.y);
    }
    @Override
    public int hashCode() {
        int result = x.hashCode();
        result = 31 * result + y.hashCode();
        return result;
    }
}


推荐答案

简单回答是首先洗牌:

List<Tuple<Integer, String>> copy = new ArrayList<>(list);
Collections.shuffle(copy);
Tuple<Integer, String> largestTuple = Collections.max(copy, Comparator.comparingInt(t -> t.x)); // credit @Holger

max()返回的元素受到遭遇订单的影响,因此洗牌有效地使其随机。

The element returned by max() is influenced by encounter order, so shuffling effectively makes it random.

如果列表不是太大(不是数千个元素),则洗牌将是非常快。

If the list is not too big (not thousands of elements), the shuffle will be pretty fast.

我制作了一份清单副本,以免影响原始清单的顺序。如果这不重要,只需使用原始列表进行随机播放。

I made a copy of the list so as to not affect the order of the original list. If that isn't important, just shuffle as use the original list.

这篇关于如何选择集合中最大的元素之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆