Home > Mobile >  How to Get the Latest Updated Values from List in Java?
How to Get the Latest Updated Values from List in Java?

Time:09-23

Here I am trying to get the latest modifieddate , Like suppose my entity class is returning 1 value or more then 1 value in that case I need to get the the latest datavalue according to lastmodifiedDate ,

This is my entity class

private String data;
private String dataValue;
private Long lastModifiedDate;

Here is my service class ..

 public void finddata(String id) {
     
            List<Entity> entity =  productRepository.findbyIdAndValue(id,value);
            
               if ((entity != null) && !entity.isEmpty()){
                for (int i = 0; i < product.size(); i  ) {
                  entity.get(i).getLastModifiedDate();
                }
            }
        }
    }
}

CodePudding user response:

If your repository is referring to a database it would be best to do the filtering right on the query side.

Otherwise you could use Stream.max() here however:

Optional<Entity> e = entity.stream()
        .max(Comparator.comparing(Entity::getLastModifiedDate));

Note that this will throw an NPE for entities without lastModifiedDate.

  • Related