List difference in java

前端 未结 11 1762
野的像风
野的像风 2020-11-30 04:33

I have two ArrayList as follows:

original: 12, 16, 17, 19, 101

selected: 16, 19, 107, 108, 109

相关标签:
11条回答
  • 2020-11-30 05:08
    List<Integer> original = Arrays.asList(12,16,17,19,101);
    List<Integer> selected = Arrays.asList(16,19,107,108,109);
    
    ArrayList<Integer> add = new ArrayList<Integer>(selected);
    add.removeAll(original);
    System.out.println("Add: " + add);
    
    ArrayList<Integer> remove = new ArrayList<Integer>(original);
    remove.removeAll(selected);
    System.out.println("Remove: " + remove);
    

    Output:

    Add: [107, 108, 109]
    Remove: [12, 17, 101]
    

    Uses Collection's removeAll method. See javadocs.

    0 讨论(0)
  • 2020-11-30 05:14

    As an alternative, you could use CollectionUtils from Apache commons library. It has static intersection, union and subtract methods suitable for your case.

    0 讨论(0)
  • 2020-11-30 05:18

    Use this method if you want to get intersection of a list of lists

    List<Address> resultsIntersectionSet( List<Set<Address>> inputListOfLists )
    {
        Set<Address> intersection = new HashSet<>();
    
        if ( !inputListOfLists.isEmpty() )
            intersection = inputListOfLists.get( 0 );
    
        for ( Set<Address> filterResultList : inputListOfLists )
        {
            intersection.retainAll( filterResultList );
        }
    
        return new ArrayList<>( intersection );
    }
    
    0 讨论(0)
  • 2020-11-30 05:19
     List<Integer> original;
     List<Integer> selected;
    
     List<Integer> add = new ArrayList<Integer>(selected);
     add.removeAll(original);
    
     List<Integer> remove = new ArrayList<Integer>(original);
     remove.removeAll(selected);
    

    Be careful with border cases around duplicate elements. Should cardinality be respected? As in, if I had 5, 6 originally and 5, 5, 6 after, should add be 5? The above works better with Sets, since they don't have duplicates (plus contains() lookups are faster since they are indexed by the data they contain).

    0 讨论(0)
  • 2020-11-30 05:20

    For intersection and union operations the natural collection type is a Set rather than a List, its also more efficient to use.

    0 讨论(0)
提交回复
热议问题