Java: 如何使用foreach对列表进行排序?

huangapple go评论83阅读模式
英文:

Java: How to sort a list using foreach?

问题

以下是翻译好的部分:

我一直在尝试在使用Java的foreach循环后对筛选列表进行排序,但我做不到。有人可以帮帮我吗?拜托了。这是我目前的代码,我应该对其进行排序:

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

以下是我打印出来的内容:

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

非常感谢!

英文:

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&lt;Photo&gt; photos = getAllPhoto();
String parteTitulo = &quot;ipsam do&quot;;
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!

答案1

得分: 1

你不能在仅迭代列表时对其进行排序。因为你无法确定在不知道列表中后续内容的情况下,某个项目是否处于正确的位置以便打印出来。所以,

你需要分为两个步骤进行 -

  1. 首先筛选列表
  2. 使用比较器对筛选后的列表进行排序
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());
}
英文:

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&lt;Photo&gt; photos = getAllPhoto();
    String parteTitulo = &quot;ipsam do&quot;;
    
    List&lt;Photo&gt; filteredPhotos = new ArrayList&lt;&gt;();
    
    for (Photo aux : photos) {
        if (aux.getTitle().contains(parteTitulo)) {
            filteredPhotos.add(aux);
        }
    }
    
    filteredPhotos.sort((p1, p2) -&gt; p1.getTitle().compareToIgnoreCase(p2.getTitle()));
    
    for (Photo aux : filteredPhotos) {
        System.out.println(aux.getTitle());
    }
    

huangapple
  • 本文由 发表于 2020年3月15日 11:38:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/60689510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定