Intersection and union of ArrayLists in Java

后端 未结 24 2174
离开以前
离开以前 2020-11-22 06:05

Are there any methods to do so? I was looking but couldn\'t find any.

Another question: I need these methods so I can filter files. Some are AND filter

相关标签:
24条回答
  • 2020-11-22 06:46

    If the number matches than I am checking it's occur first time or not with help of "indexOf()" if the number matches first time then print and save into in a string so, that when the next time same number matches then it's won't print because due to "indexOf()" condition will be false.

    class Intersection
    {
    public static void main(String[] args)
     {
      String s="";
        int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
        int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};
    
    
           for (int i = 0; i < array1.length; i++)
           {
               for (int j = 0; j < array2.length; j++)
               {
                   char c=(char)(array1[i]);
                   if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
                   {    
                    System.out.println("Common element is : "+(array1[i]));
                    s+=c;
                    }
               }
           }    
    }
    

    }

    0 讨论(0)
  • 2020-11-22 06:47
    list1.retainAll(list2) - is intersection
    

    union will be removeAll and then addAll.

    Find more in the documentation of collection(ArrayList is a collection) http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collection.html

    0 讨论(0)
  • 2020-11-22 06:49

    Here's a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don't modify the original lists input to the methods.

    public class Test {
    
        public static void main(String... args) throws Exception {
    
            List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
            List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
    
            System.out.println(new Test().intersection(list1, list2));
            System.out.println(new Test().union(list1, list2));
        }
    
        public <T> List<T> union(List<T> list1, List<T> list2) {
            Set<T> set = new HashSet<T>();
    
            set.addAll(list1);
            set.addAll(list2);
    
            return new ArrayList<T>(set);
        }
    
        public <T> List<T> intersection(List<T> list1, List<T> list2) {
            List<T> list = new ArrayList<T>();
    
            for (T t : list1) {
                if(list2.contains(t)) {
                    list.add(t);
                }
            }
    
            return list;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:49

    This post is fairly old, but nevertheless it was the first one popping up on google when looking for that topic.

    I want to give an update using Java 8 streams doing (basically) the same thing in a single line:

    List<T> intersect = list1.stream()
        .filter(list2::contains)
        .collect(Collectors.toList());
    
    List<T> union = Stream.concat(list1.stream(), list2.stream())
        .distinct()
        .collect(Collectors.toList());
    

    If anyone has a better/faster solution let me know, but this solution is a nice one liner that can be easily included in a method without adding a unnecessary helper class/method and still keep the readability.

    0 讨论(0)
  • 2020-11-22 06:49

    I think you should use a Set to hold the files if you want to do intersection and union on them. Then you can use Guava's Sets class to do union, intersection and filtering by a Predicate as well. The difference between these methods and the other suggestions is that all of these methods create lazy views of the union, intersection, etc. of the two sets. Apache Commons creates a new collection and copies data to it. retainAll changes one of your collections by removing elements from it.

    0 讨论(0)
  • 2020-11-22 06:49

    Here is a way how you can do an intersection with streams (remember that you have to use java 8 for streams):

    List<foo> fooList1 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
    List<foo> fooList2 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
    fooList1.stream().filter(f -> fooList2.contains(f)).collect(Collectors.toList());
    

    An example for lists with different types. If you have a realtion between foo and bar and you can get a bar-object from foo than you can modify your stream:

    List<foo> fooList = new ArrayList<>(Arrays.asList(new foo(), new foo()));
    List<bar> barList = new ArrayList<>(Arrays.asList(new bar(), new bar()));
    
    fooList.stream().filter(f -> barList.contains(f.getBar()).collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题