简体   繁体   中英

Easiest way to check 4 Arraylists in java do not contain the same values

I think the title says it all, but

List<Integer> stack ;
List<Integer> exchange;
List<Integer> quora;

A value in stack can not be in exchange or quoroa, a value in exchange can not be in stack and quora, and so on.

Construct a Set full of your elements with some Guava glue and then compare the sizes:

final Iterable<Integer> all = Iterables.concat(stack, exchange, quora, ...);
final Set<Integer> unique = Sets.newHashSet(all);

if (Iterables.size(all) > unique.size()) {
    // inputs contain duplicate(s)
}

Use Sets to see if there are duplicates.

HashSet<Integer> stackSet = new HashSet<>(stack);
HashSet<Integer> exchangeSet = new HashSet<>(exchange);
HashSet<Integer> quoraSet = new HashSet<>(quora);

if(stackSet.removeAll(quoraSet))
    ; // Error, there were common elements!

How do you like subtract from CollectionUtil ? Don't know if it is the best way, but it is definitely a very easy approach!

Rationally, you can do something like intersection of sets, so that to make sure there is no intersection. It should look more meaningful:

By using Guava library:

HashSet<Integer> stackSet = new HashSet<>(stack);
HashSet<Integer> exchangeSet = new HashSet<>(exchange);

if (! Sets.intersect(stackSet, exchangeSet).isEmpty()) {
    // there is intersection between stackSet and exchangeSet
}

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