简体   繁体   English

如何在java中比较两个通用列表的元素?

[英]How to compare elements of two generic lists in java?

I have two generic list of Data Type class:RequiredList & PrimaryList 我有两个通用的数据类型列表:RequiredList和PrimaryList

   public class Data{
        private String dataCode;
        private String dataDesc; 

        public String getDataCode(){}

        public void setDataCode(String dataCode){}

        public String getDataDesc(){}

        public void setDataDesc(String dataDesc){}


        }

    public static void main(String[] args) {
        List<Data> primaryList = new ArrayList<Data>();
        for (int i = 2; i < 5; i++) {
            Data data = new Data();
            data.setDataCode("code" + i);
            data.setDataDesc("desc" + i);
            primaryList.add(data);
        }

        List<Data> requiredList = new ArrayList<Data>();
        for (int i = 0; i < 8; i++) {
            Data data = new Data();
            data.setDataCode("code" + i);
            data.setDataDesc("desc" + i);
            requiredList.add(data);

        }
        StringBuffer partyList = new StringBuffer();
        for (int i = 0; i < requiredList.size(); i++) {
            if (primaryList.size() > i
                    && !requiredList.get(i).getDataCode().equals(primaryList.get(i).getDataCode())) {
                partyList.append(requiredList.get(i).getDataDesc());
                partyList.append(",");

            }
            if(primaryList.size() <= i)
            {
                partyList.append(requiredList.get(i).getDataDesc());
                partyList.append(",");
            }           
        }
        System.out.println(partyList.toString());
    }

I want to compare elements of requiredList to elements of primaryList.Those elements of primaryList are not present in requiredList , they will be added in new list.Can anybody help me out? 我想将requiredList的元素与primaryList的元素进行比较。在requiredList中不存在primaryList的元素,它们将被添加到新列表中。任何人都可以帮助我吗?

First you need to implement equals() and hashcode() for Data 首先,您需要为Data实现equals()hashcode()

Then 然后

List<Data> newlist = new ArrayList<Data>();
for(Data data : primaryList ) {
   if(!requiredList.contains(data) ) {
       newlist.add(data);
   }
 } 

If you okay to modify primaryList then removeAll would do the trick 如果你可以修改primaryList,那么removeAll就可以了

primaryList.removeAll(requiredList);

As @Subin S pointed out equals and hashCode need to be overriden for Data . 由于@Subin S指出equalshashCode需要覆盖Data

Those elements of primaryList are not present in requiredList , they will be added in new list. primaryList中的那些元素不存在于requiredList中,它们将被添加到新列表中。

Look at the List removeAll() or retainAll() methods are useful in your usecase. 查看List removeAll()retainAll()方法在您的用例中很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM