[英]Get the element with the highest priority based on another list in Java
我有一份優先事項清單
List<String> priorities = Arrays.asList("NV","PH","OO","DR");
我有一個 Items List<Item> availableItems
,其中 Item 有一個名為type
的屬性,它可以是第一個列表中的值之一。
所以我正在研究一種方法,它返回一個元素(最高優先級),我正在用比較器和排序做一些事情,但我正在閱讀它,據說這需要很多時間,因為availableItems
可以有很多元素,所以它可能是O(NLogN)
。
我想要實現的是,如果有一個type
NV
的元素返回是因為是最高優先級,如果不是具有PH
的元素,依此類推,如果沒有一個元素,則返回列表中的任何元素,因為他們沒有,但沒有使用比較器或成本不高
基於@Gilbert Le Blanc評論。
TreeMap<Integer, List<Item0>> groupByType = availableItems.stream()
.collect(Collectors.groupingBy(item -> priorities.indexOf(item.getType()),
TreeMap::new, Collectors.toList()));
System.out.println(groupByType.firstEntry().getValue().get(0));
我建議將PriorityQueue
與基於索引的比較器一起使用:
public static <T> Comparator<T> comparatorByIndex(List<T> list) {
Map<T, Integer> priority = IntStream.range(0, list.size()).boxed().collect(Collectors.toMap(list::get, Function.identity()));
return Comparator.comparing(k -> priority.getOrDefault(k, Integer.MAX_VALUE));
}
並獲得具有最高優先級的字符串,例如:
List<String> priorities = Arrays.asList("NV","PH","OO","DR");
Queue<String> priorityOrder = new PriorityQueue<>(comparatorByIndex(priorities));
priorityOrder.addAll(availableItems);
String highestPriority = priorityOrder.poll();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.