Java: How to sort a list using foreach?

isebastianvp :

I've been trying to sort a filtered list once I use foreach in Java, but I can't. Could someone help me? Please. This is the code I have and I should sort:

List<Photo> photos = getAllPhoto();
String parteTitulo = "ipsam do";
for (Photo aux: photos){
    if(aux.getTitle().contains(parteTitulo)){
        System.out.println(aux.getTitle());
    }
}

This is what I get once I print it:

placeat ipsam doloremque possimus sint autem laborum ea expedita
sed ut aut ipsam dolore
beatae ipsam dolores consequatur eum quia inventore sit
eos sapiente ipsam dolores accusamus est et nihil odio
consequatur iure est ullam ipsam dolorem nesciunt

Thank you very much!

shakhawat :

You can not sort a list while just iterating it. Because you can't decide whether it's the right position of an item to print out without knowing what is ahead in the list. So

You have to do it in 2 steps -

  1. First filter the list
  2. Sort the filtered list using a comparator

    List<Photo> photos = getAllPhoto();
    String parteTitulo = "ipsam do";
    
    List<Photo> filteredPhotos = new ArrayList<>();
    
    for (Photo aux : photos) {
        if (aux.getTitle().contains(parteTitulo)) {
            filteredPhotos.add(aux);
        }
    }
    
    filteredPhotos.sort((p1, p2) -> p1.getTitle().compareToIgnoreCase(p2.getTitle()));
    
    for (Photo aux : filteredPhotos) {
        System.out.println(aux.getTitle());
    }
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=277691&siteId=1