How to remove duplicate objects in a List without equals/hashcode?

后端 未结 21 1656
渐次进展
渐次进展 2020-12-03 02:53

I have to remove duplicated objects in a List. It is a List from the object Blog that looks like this:

public class Blog {
    private String title;
    priv         


        
21条回答
  •  没有蜡笔的小新
    2020-12-03 03:17

    This can be logically solved using a property. Here I have a property called a key.

    1. Take out any String property in the object and put it in the list.
    2. Check in the list weather that property contains if so then remove it.
    3. Return the object list.

    List objectList = new ArrayList<>();
     List keyList = new ArrayList<>();
      objectList.forEach( obj -> {
       if(keyList.contains(unAvailabilityModel.getKey())) 
             objectList.remove(unAvailabilityModel); 
        else
            keyList.add(unAvailabilityModel.getKey();
    });
    return objectList;
    
        

    提交回复
    热议问题