'Compare two Lists and get the difference [duplicate]
I have two Lists which I get - one from xlsx file, the second one - by select from database
@Component
public class ReadExcelDemo implements CommandLineRunner {
@Autowired
private TakeDataService dataService;
private List<Integer> list;
private List<TakeData> dates;
@Override
public void run(String... args) {
try
{
FileInputStream file = new FileInputStream("Report.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (cell.getColumnIndex() == 0) {
list = new ArrayList<>();
list.add((int) cell.getNumericCellValue());
//System.out.println(list);
}
}
}
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
takeData();
printDifference();
}
public void takeData() {
dates = new ArrayList<>(dataService.takeData());
// System.out.println(dates);
}
public void printDifference() {
List<Integer> id = dates.stream().map(TakeData::getId).collect(Collectors.toList());
// for (Integer a : list) {
// id.remove(a);
// }
//List<Integer> difference = new ArrayList<>(CollectionUtils.disjunction(list, id));
Set<Integer> diff = new HashSet<>(id);
System.out.println(list.stream().filter(((Predicate<? super Integer>) diff :: contains).negate()).collect(Collectors.toList()));
}
}
I need to find the difference between these Lists and just print the result of this difference to the console. I have already tried many routers, but most likely it's not the implementation, but something else.
Solution 1:[1]
If you're using apache common-collections, try using the below, otherwise there's plenty other options shared in Joe's link
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 4, 5);
Collection<Integer> list1WithoutList2 = CollectionUtils.removeAll(list1, list2);
System.out.println(list1WithoutList2); //Prints 2,3
Collection<Integer> list2WithoutList1 = CollectionUtils.removeAll(list2, list1);
System.out.println(list2WithoutList1); //Prints 4,5
System.out.println(Stream.concat(list1WithoutList2, list2WithoutList1).toSet()); //Prints 2,3,4,5
Solution 2:[2]
Plain Java implementation:
public static void main(String[] args) {
List<Integer> list = List.of(1,2,3,4,5);
List<Integer> target = List.of(1,2,3,40,50);
List<Integer> result = list.stream().filter(v -> !target.contains(v)).collect(Collectors.toList());
// Prints [4, 5] - items in the list not found in the target
System.out.println(result);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jbk |
Solution 2 |