简体   繁体   中英

Sort List of Objects Based On Another Sorted List Object Positions In Java

I have two list objects like :

public class AttributeMaster {
    public String attribute_id;
    public String view_index;
    ...
}

List<AttributeMaster> attributes = new ArrayList<AttributeMaster>();

public class AttributeDetail {
    public String attribute_id;
    public String attribute_name;
    ...
}

List<AttributeDetail> attribute_detail = new ArrayList<AttributeDetail>();

Here, I need to sort attribute_detail list based on list attributes . List attribute is already sorted based on its view_index property. I want to update second list based on index of attribute_master list.

If one one can help.

Collections.sort(attribute_detail, 
    Comparator.comparing(item -> attributes.indexOf(item)));
int start_index=0;
for(int i=0;i<attributes.size();i++) {

    for(int j=0;j<attribute_detail.size();j++) {
        if(attributes.get(i).getAttribute_id().equals(attribute_detail.get(j).getAttribute_id())){

            AttributeDetail temp=attribute_detail.get(start_index);
            attribute_detail.set(start_index, attribute_detail.get(j));
            attribute_detail.set(j,temp);
            start_index++;
        }
    }
}

Through index iterations, the code will check the object existence for both list using attribute_id. If the object present in both list, then it will sort the list of attribute_detail based on the index of attributes list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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