简体   繁体   中英

Check 2 sets and get all removed/added form/to first set elements

I have 2 Sets and I need equals this sets and get removed and added elements. I do it

public static void main(String[] args) {
        System.out.println("start");
        Set<String> setDestOrigin = new HashSet<>();
        Set<String> setLocalOrigin = new HashSet<>();

        setDestOrigin.add("test1");
        setDestOrigin.add("test2");
        setDestOrigin.add("test3");
        setDestOrigin.add("test7");
        setDestOrigin.add("test5");

        setLocalOrigin.add("test1");
        setLocalOrigin.add("test2");
        setLocalOrigin.add("test3");
        setLocalOrigin.add("test4");
        setLocalOrigin.add("test5");


        Set<String> deleted = new HashSet<>(setLocalOrigin);
        deleted.removeAll(setDestOrigin);

        Set<String> added = new HashSet<>(setDestOrigin);
        added.removeAll(setLocalOrigin);

        System.out.println("finish");
    }

In deleted set I have all element each was removed from setDestOrigin In added set I have all element each was added to setDestOrigin

Is there a way to do the same thing easier?

Your approach looks like correct one. You also could try Guava's Sets.difference(set1, set2). It returns an unmodifiable view which implements Set interface.

If you have Guava, you can use Sets.difference() , which returns a view of the difference between two sets. This can be more efficient than copying and removing elements. They also have convenient utilities for initializing collections:

Set<String> setDestOrigin = ImmutableSet.of("test1", "test2", "test3", "test7", "test5");
Set<String> setLocalOrigin = ImmutableSet.of("test1", "test2", "test3", "test4", "test5");

Set<String> deleted = Sets.difference(setLocalOrigin, setDestOrigin);
Set<String> added = Sets.difference(setDestOrigin, setLocalOrigin);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM