简体   繁体   中英

How to check if aspecified object exists in a given list of object or not with java

I am using java 11 and i want to check if a object exist in list of object i use

   List<MenuDTO> menuDTO=new ArrayList<>();
   MenuDTO menu=menuData.findByIdMenu(menuItemDTO.getMenuid());

   if(menuDTO.contains(menu)){
                    menuItemResult.add(menuItemDTO);
                    menu.setMenuitems(menuItemResult);
   }

But it return always false even the list contain the element

I don't know if this is what you are looking for, but maybe this can help:

List<MenuDTO> menuDTO=new ArrayList<>();
MenuDTO menu=menuData.findByIdMenu(menuItemDTO.getMenuid());
boolean doesExists = menuDTO.stream().anyMatch(menuElement -> menuElement.getMenuId() == menu.getMenuId());
if(doesExists){
    menuItemResult.add(menuItemDTO);
    menu.setMenuitems(menuItemResult);
}
 

Java collections contains use object equals methods to determine if specified object is in the collection, so you need to implement it for objects that you use in collections. Here is some guide on how to implement equals and hashCode methods on objects:

Java equals() and hashCode() Contracts

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