比较两个列表并在至少一个条目相同时返回错误

时间:2021-10-29 18:23:10

I have an object SalesType with fields SalesTypeId and SalesTypeCode.

我有一个对象SalesType,其字段为SalesTypeId和SalesTypeCode。

I have two lists list1 and list2.

我有两个列表list1和list2。

List1={(1,10),(2,20),(3,30)}
List2={(1,40),(2,50),(3,20)

I am trying to compare the SalesTypeCode code in the lists and if it is same then it has to exit the loop and return lists has same field.

我试图比较列表中的SalesTypeCode代码,如果它是相同的,那么它必须退出循环并且返回列表具有相同的字段。

Below is what I did but it is not returning what I am expecting.

以下是我的所作所为,但它没有回归我所期待的。

What did I do wrong?

我做错了什么?

List<SalesType> list1 =service.getAllSalesTypeCodes(form.getReqSalesTypeGroup());
        List<SalesType> list2 = service.getAllSalesTypeCodes(form.getSorSalesTypeGroup());
        if (list1 != null || list2 != null) {
            mainLoop:
            for (int i = 0; i < list2.size(); i++) {
                System.out.println("list2 " + list2.get(i).getSalesTypeCode());
                for (int j = 0; j < list1.size(); j++) {
                    System.out.println("list1 " + list1.get(j).getSalesTypeCode());
                    if ((list2.get(i).getSalesTypeCode()).equals((list1.get(j).getSalesTypeCode()))) {
                        System.out.println("equals..:" + (list2.get(i).getSalesTypeCode()).equals((list1.get(j).getSalesTypeCode())));
                    errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ActionErrorConstants.MESSAGE_EXISTS_SALES_TYPE));
                        System.out.println("breaking the loop");
                        break mainLoop;
                }
                }
            }

        }

1 个解决方案

#1


1  

Override properly equals in the SalesType class (including HashCode) and then use

在SalesType类(包括HashCode)中正确覆盖等于然后使用

  • List#retainAll(...) method

    or

  • 列表#retainAll(...)方法或

  • List#.removeAll(... ) method
  • 列表#.removeAll(...)方法

#1


1  

Override properly equals in the SalesType class (including HashCode) and then use

在SalesType类(包括HashCode)中正确覆盖等于然后使用

  • List#retainAll(...) method

    or

  • 列表#retainAll(...)方法或

  • List#.removeAll(... ) method
  • 列表#.removeAll(...)方法