Skip to content

Instantly share code, notes, and snippets.

@Longwater1234
Last active October 30, 2021 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Longwater1234/6beb271ca6fc9c5e501721ab9f279e1f to your computer and use it in GitHub Desktop.
Save Longwater1234/6beb271ca6fc9c5e501721ab9f279e1f to your computer and use it in GitHub Desktop.
Inverse Compare Hashmap ArrayList
public class InverseCompare {
public static final String ID = "id";
public static final String ANIMALNAME = "animalName";
public static void main(String[] args) {
ArrayList<Map<String, Object>> myList = new ArrayList<>(4); // what we have now.
Map<String, Object> map0 = new HashMap<>();
Map<String, Object> map1 = new HashMap<>();
map0.put(ANIMALNAME, "dog");
map0.put(ID, (int) (Math.random() * 100 - 10) + 10);
map1.put(ANIMALNAME, "cat");
map1.put(ID, (int) (Math.random() * 100 - 10) + 10);
//add random data, in a random fashion
myList.add(map1);
myList.add(map0);
List<String> a1 = Arrays.asList("dog", "cat", "zebra", "duck", "cow"); // from database.
List<String> a3 = new ArrayList<>();
for (String s : a1) {
Set<String> uniqueValues = new HashSet<>();
for (Map<String, Object> kk : myList) {
if (!s.equals(kk.get(ANIMALNAME))) {
if (uniqueValues.add(s)) {
a3.add(s);
}
}
}
}
// GOAL: FILTER absent from on our hand.
// formula: absent = database - OnHand
System.out.println(a3);
}
}
@Longwater1234
Copy link
Author

Longwater1234 commented Oct 28, 2021

or alternative (shorter, using Streams:

List<String> a3 = new ArrayList<>();
       for (String s : a1) {
           myList.stream()
                   .filter(kk -> !s.equals(kk.get(ANIMALNAME)))
                   .map(kk -> s)
                   .distinct()
                   .forEach(a3::add);
       }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment