網(wǎng)站在線客服鏈接如何做一個(gè)網(wǎng)站
🎈邊走、邊悟🎈遲早會(huì)好 |
????????在Java中實(shí)現(xiàn)這個(gè)功能,可以使用Stream
來篩選出符合條件的元素,將它們放在新集合的前面,同時(shí)保留其他元素在新集合的后面。以下是如何實(shí)現(xiàn)的代碼示例:
代碼示例:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;class Crop {String a;int b;Crop(String a, int b) {this.a = a;this.b = b;}@Overridepublic String toString() {return "Crop{" + "a='" + a + '\'' + ", b=" + b + '}';}
}public class Main {public static void main(String[] args) {List<Crop> crops = new ArrayList<>();crops.add(new Crop("水稻", 100));crops.add(new Crop("玉米", 200));crops.add(new Crop("小麥", 300));crops.add(new Crop("大豆", 400));crops.add(new Crop("高粱", 500));List<String> priorityOrder = List.of("大豆", "小麥", "玉米");// 篩選出符合條件的對(duì)象并組成新集合的前部分List<Crop> priorityCrops = crops.stream().filter(crop -> priorityOrder.contains(crop.a)).sorted((c1, c2) -> {int index1 = priorityOrder.indexOf(c1.a);int index2 = priorityOrder.indexOf(c2.a);return Integer.compare(index1, index2);}).collect(Collectors.toList());// 篩選出不符合條件的對(duì)象并組成新集合的后部分List<Crop> otherCrops = crops.stream().filter(crop -> !priorityOrder.contains(crop.a)).collect(Collectors.toList());// 將兩個(gè)集合合并成一個(gè)新集合List<Crop> newCrops = new ArrayList<>();newCrops.addAll(priorityCrops);newCrops.addAll(otherCrops);// 打印新集合for (Crop crop : newCrops) {System.out.println(crop);}}
}
代碼解釋:
Crop
類:包含字段a
和b
,a
是要篩選和排序的字段。priorityOrder
:指定你要優(yōu)先篩選和排序的字段值,如“大豆”、“小麥”、“玉米”。priorityCrops
:使用Stream
的filter
方法篩選出a
字段在priorityOrder
中的對(duì)象,并根據(jù)priorityOrder
中的順序排序。otherCrops
:篩選出不符合priorityOrder
條件的對(duì)象。newCrops
:將priorityCrops
和otherCrops
合并,形成一個(gè)新的集合。- 打印新集合:按順序輸出新集合的內(nèi)容。
最終輸出結(jié)果:?
Crop{a='大豆', b=400}
Crop{a='小麥', b=300}
Crop{a='玉米', b=200}
Crop{a='水稻', b=100}
Crop{a='高粱', b=500}
?新集合newCrops
中,a
字段為“大豆”、“小麥”、“玉米”的對(duì)象會(huì)排在前面,其他對(duì)象會(huì)排在后面。
?
?🌟感謝支持?聽?wèi)?-CSDN博客
🎈眾口難調(diào)🎈從心就好 |