java中如何做并集、交集、差集和反向数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3590677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:17:01  来源:igfitidea点击:

How to do union, intersect, difference and reverse data in java

java

提问by Giffary

I want to implement the union, intersect, difference and reverse operations in Java.

我想在Java中实现并集、交集、差集和反向操作。

First I have 2 instances of ArrayList<Integer>

首先我有2个实例 ArrayList<Integer>

a = [0,2,4,5,6,8,10]
b = [5,6,7,8,9,10]

a union b should return c = [0,2,4,5,6,7,8,9,10]

a union b 应该返回 c = [0,2,4,5,6,7,8,9,10]

a intersect b should return c = [5,8,10]

a 相交 b 应该返回 c = [5,8,10]

a difference b should return c = [0,2,4]

差异 b 应该返回 c = [0,2,4]

reverse a = [10,8,6,5,4,2,0]

逆转 a = [10,8,6,5,4,2,0]

Something like this.

像这样的东西。

How to implement that method in Java?

如何在 Java 中实现该方法?



Update: I have to start with this template:

更新:我必须从这个模板开始:

package IntSet;
import java.util.ArrayList;
import java.util.Collection;


public class IntSet {

private ArrayList<Integer> intset;

public IntSet(){
    intset = new ArrayList<Integer>();
}

public void insert(int x){
    intset.add(x);
}

public void remove(int x){
    //implement here
    intset.indexOf(x);
}

public boolean member(int x){
    //implement here
    return true;
}

public IntSet intersect(IntSet a){
    //implement here
    return a;
}

public IntSet union(IntSet a){
    //implement here
    return a;
}

public IntSet difference(IntSet a){
    //implement here
    IntSet b = new IntSet();
    return b; 
}

采纳答案by anand

//Union 
List<Integer> c = new ArrayList<Integer>(a.size() + b.size());
addNoDups(c,a);
addNoDups(c,b);

private void addNoDups(List<Integer> toAddTo,List<Integer> iterateOver) {
    for(Integer num:iterateOver){
        if(toAddTo.indexOf(num) == -1) {
            toAddTo.add(num);
        }
    }
}

//intersection
List<Integer> c = new ArrayList<Integer> (a.size() > b.size() ?a.size():b.size());
c.addAll(a);
c.retainAll(b);

//difference a-b
List<Integer> c = new ArrayList<Integer> (a.size());
c.addAll(a);
c.removeAll(b);

回答by Landei

First, the operations you describe (except reverse) are set operations, not list operations, so use HashSet or (if you need an ordering) TreeSet.

首先,您描述的操作(反向除外)是设置操作,而不是列表操作,因此请使用 HashSet 或(如果需要排序)TreeSet。

    Set<Integer> a = new TreeSet<Integer>(Arrays.asList(new Integer[]{0,2,4,5,6,8,10}));
    Set<Integer> b = new TreeSet<Integer>(Arrays.asList(new Integer[]{5,6,7,8,9,10}));

    //union
    Set<Integer> c = new TreeSet<Integer>(a);
    c.addAll(b);
    System.out.println(c);

    //intersection
    Set<Integer> d = new TreeSet<Integer>(a);
    d.retainAll(b);
    System.out.println(d);

    //difference
    Set<Integer> e = new TreeSet<Integer>(a);
    e.removeAll(b);
    System.out.println(e);

    //reverse
    List<Integer> list = new ArrayList<Integer>(a);
    java.util.Collections.reverse(list);
    System.out.println(list);

回答by atk

A lot of the answers tell you to use libraries that will do the work for you. While this is the right solution for the real world, keep in mind hat you're doing homework, and your teacher probably wants you to understand how the functions are written, not just how to find libraries to do the work for you.

很多答案都告诉您使用可以为您完成工作的库。虽然这是现实世界的正确解决方案,但请记住,您正在做家庭作业,并且您的老师可能希望您了解函数是如何编写的,而不仅仅是如何找到库来为您完成工作。

That said, you've got a good start with the code you've shown. Let's take the problem one step at a time.

也就是说,您已经从展示的代码中获得了良好的开端。让我们一步一步解决这个问题。

First, do you know where the Java documentation is located? http://download.oracle.com/javase/1.4.2/docs/api/this is critical, as this is how you find out what functions do what. Here's the link to Java 1.4. I didn't notice what version you're using, but Java is backward compatible, so this should be sufficient.

首先,你知道Java文档在哪里吗?http://download.oracle.com/javase/1.4.2/docs/api/这很关键,因为这是您找出哪些功能做什么的方式。这是 Java 1.4 的链接。我没有注意到您使用的是什么版本,但 Java 向后兼容,所以这应该足够了。

In the docs, find the ArrayList entry.

在文档中,找到 ArrayList 条目。

Now that we've got the API docs, we need to break down your question. you've posted code, so I'll address it function by function.

现在我们已经有了 API 文档,我们需要分解您的问题。您已经发布了代码,所以我将逐个处理它。

insert() : do you have to have an ordered list, or does order not matter? Or are you guaranteed that values will be provided to you in order? Have you learned sorting algorithms yet?

insert() :你必须有一个有序列表,还是顺序无关紧要?或者您是否保证将按顺序向您提供值?你学过排序算法吗?

remove() : this function doesn't work. take a look at the ArrayList API and see how to remove an item from the list. Use that method.

remove() :此功能不起作用。查看 ArrayList API 并了解如何从列表中删除项目。用那个方法。

member() : your member method doesn't work. You need to check every entry of the list and determine if the current member matches the function argument. Have you learned about for loops?

member() :您的成员方法不起作用。您需要检查列表的每个条目并确定当前成员是否与函数参数匹配。你学过for循环吗?

intersect() : ok, tell me in English what intersect is supposed to do. Don't use the teacher's description if you can help it - use your own words (note to others, this is an exercise for the OP to learn to program, so please don't go answering it for him)

intersect() :好的,用英语告诉我 intersect 应该做什么。能帮忙的就不要用老师的描述——用你自己的话(注意别人,这是OP学习编程的练习,所以请不要去替他回答)

difference() : again, tell me in English what it's supposed to do.

差异():再次,用英语告诉我它应该做什么。

reverse() : again, give me the English description of what this is supposed to do.

reverse() :再次,给我这个应该做什么的英文描述。

Once you have english descriptions, describe an algorithm that can do the work. don't write it in Java yet. just write an algorithm, in english, describing how you would do the work manaully, with pen and paper.

一旦你有了英文描述,就描述一个可以完成这项工作的算法。不要用Java编写它。只需用英语编写一个算法,描述您将如何使用笔和纸手动完成工作。

at this point, try and convert the algorithm to Java code.

此时,尝试将算法转换为 Java 代码。

回答by Sean Patrick Floyd

If you are using Sets (as you should, for all of those except reverse are Set operations), Guavaprovides these operations in it's Setsclass.

如果您正在使用 Sets(正如您应该的那样,除了反向操作之外的所有操作都是 Set 操作),Guava在它的Sets类中提供了这些操作。

Set<Integer> union = Sets.union(set1, set2);
Set<Integer> intersection = Sets.intersection(set1, set2);
Set<Integer> difference = Sets.difference(set1, set2);

All of these return unmodifiable views, backed by the original Sets.

所有这些都返回不可修改的视图,由原始 Sets 支持。

See Guava Explained-> Collection Utilities-> Sets

参见Guava Explained-> Collection Utilities-> Sets

If Lists are what you have, you can convert them to a Set by using the copy constructor present in all standard collections:

如果您拥有的是列表,则可以使用所有标准集合中存在的复制构造函数将它们转换为集合:

List<X> list = new ArrayList<>();
// fill up list here
Set<X> set = new HashSet<>(list);

回答by An Nguyen

This snippet will find the union of two collections using apache commons CollectionUtils.union method

此代码段将使用 apache commons CollectionUtils.union 方法找到两个集合的并集

Collection<String> totalFriends = CollectionUtils.union(yourFriends, myFriends);

回答by Anton Balaniuc

I just will leave it here. There is a new way with java-8and streams

我只会把它留在这里。有一种新的方式java-8streams

List<Integer> listA = Arrays.asList(0, 2, 4, 5, 6, 8, 10);
List<Integer> listB = Arrays.asList(5, 6, 7, 8, 9, 10);

List<Integer> intersection = listA.stream()
        .filter(listB::contains)
        .collect(Collectors.toList());

List<Integer> union = Stream.concat(listA.stream(), listB.stream())
        .distinct().sorted()
        .collect(Collectors.toList());

List<Integer> aDiffB = listA.stream()
        .filter(i -> !listB.contains(i))
        .collect(Collectors.toList());

System.out.println(intersection); // [5, 6, 8, 10]
System.out.println(union); // [0, 2, 4, 5, 6, 7, 8, 9, 10]
System.out.println(aDiffB); // [0, 2, 4]