Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按数组的第二个元素Uniquify数组列表_Java_Arraylist_Set_Unique - Fatal编程技术网

Java 按数组的第二个元素Uniquify数组列表

Java 按数组的第二个元素Uniquify数组列表,java,arraylist,set,unique,Java,Arraylist,Set,Unique,给定这样一个Arraylist: List<Integer[]> list = new Arraylist<>(); list.add(new Integer[] {13, 1}); list.add(new Integer[] {100, 2}); list.add(new Integer[] {143, 2}); list.add(new Integer[] {185, 3}); list.add(new Integer[] {111, 3}); list.add(n

给定这样一个Arraylist:

List<Integer[]> list = new Arraylist<>();
list.add(new Integer[] {13, 1});
list.add(new Integer[] {100, 2});
list.add(new Integer[] {143, 2});
list.add(new Integer[] {185, 3});
list.add(new Integer[] {111, 3});
list.add(new Integer[] {98, 4});
我如何用第一个元素的最小值对第二个元素的列表进行uniquify

通常,我会简单地将一个列表转换为一个集合,然后再次将其作为列表返回,但是我如何处理这种情况呢


提前谢谢

我不确定这是否是最好的解决方案,但您仍然可以使用一组已找到的值,然后这样做:

    Set<Integer> found=new HashSet<>();
    list.removeIf(p->!found.add(p[1]));
其思想是,无论如何,您都需要存储找到的值。您可以在streams Api中使用过滤器,但很难保持状态,您可能仍然需要维护另一个已添加值的集合。所以我认为这是一个简单的解决办法


如果给定第一个值总是100。否则,您可能需要对其进行一些修改

您可以定义一个中间对象

class Intermediate implements Comparable<Intermediate> {
    private Integer[] array;
    public Intermediate(Integer[] arr) { array = arr; }
    public boolean equals(Object o) { 
        return (o instanceof Intermediate) &&
            array[1] == ((Intermediate)o).array[1];
    }
    public int compareTo(Intermediate i) {
        return Integer.compare(array[0], i.array[0]);
    }
    public Integer[] toTarget() { return array; }
}
这是一条小溪。equals是在第二个int上定义的,因此可以使用distinct,然后映射回数组并收集

    .sorted() // make sure to take the lowest first value
    .distinct()
    .map(Intermediate::toTarget)
    .collect(toList());
或者,如果只需要数组中的第一个int

    .map(i -> i.toTarget()[0])
    .collect(toList());

这将为您的示例列表提供[13、100、111、98]。

您是否始终将100作为arraylist每个项目的第一个元素?预期输出是什么?是否保证每个数组中的第一个元素始终为100?如果不是,那么数组{200,1}和{300,1}的结果应该是什么?不,它并不总是100。在这种情况下,我会选择较小的一个。在这种情况下,使用选项并将该信息直接放在您的问题中,因为它是重要的细节。并不是每个人都会在评论部分寻找它。谢谢!我稍微修改了一下任务。如果我想用较低的第一个元素来存储条目,那该怎么办?感谢您提供的详细解决方案!我稍微修改了一下任务。很抱歉,我一开始没有这样表述…@A.Ka。我真的不知道发生了什么变化。无论如何,我更新了我的答案,如果这是你的意思的话,我只包含了数组中第一个整数的映射。我再次忘记了一个重要的事实:第一个元素的值应该是最小的。最后,我完全编辑了任务。我只对第二个元素感兴趣,但它们应该是第一个元素最低的元素。@A.Ka。但这只意味着你需要按照第一个整数对流进行升序排序。我把它放进去了。
    .map(i -> i.toTarget()[0])
    .collect(toList());