I wish I could create something like the SQL minus operator (← transmitted) between List types, and when I looked it up, Apache Commons was useful.
List<String> list1 = Arrays.asList("a", "b", "e", "f"); List<String> list2 = Arrays.asList("a", "b", "c", "d", "e"); //Extract what is in list1 but not in list2 @SuppressWarnings("unchecked") Collection<String> result = CollectionUtils.subtract(list1, list2); System.out.println(result.toString()); // => [f]
As for the contents of CollectionUtils # subtract (), it seems that ArrayList is created based on the first argument (list1), and the second argument (list2) is rotated around with an iterator to remove one by one. It seems that the order of one argument (list1) is guaranteed. However, I feel that it is correct to pack it in the appropriate data type.
I was about to mass-produce a simple and troublesome code like ↓.
List<String> result = new ArrayList<String>(list1); result.removeAll(list2);