英文:
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<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!
答案1
得分: 1
你不能在仅迭代列表时对其进行排序。因为你无法确定在不知道列表中后续内容的情况下,某个项目是否处于正确的位置以便打印出来。所以,
你需要分为两个步骤进行 -
- 首先筛选列表
- 使用比较器对筛选后的列表进行排序
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 -
-
First filter the list
-
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()); }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论