Reputation: 309
I have a list of priorities
List<String> priorities = Arrays.asList("NV","PH","OO","DR");
And I have a list of Items List<Item> availableItems
where the Item has an attribute called type
that can be one of the values from the first list.
So I am working on a method, that returns one element (the highest priority), I was doing something with a comparator and sorting, but I was reading about it and it's said it takes a lot of time since availableItems
can have a lot of elements, so it might be O(NLogN)
.
What I am trying to achieve is if there is an element with type
NV
return is since is the highest priority, if not the one with PH
and so on, and if there is no a single one, then return any element of the list, since they don't have, but without using comparators or the cost is not high
Upvotes: 0
Views: 1557
Reputation: 11740
I would suggest using a PriorityQueue
with a index-based Comparator:
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));
}
And getting the String with highest priority like:
List<String> priorities = Arrays.asList("NV","PH","OO","DR");
Queue<String> priorityOrder = new PriorityQueue<>(comparatorByIndex(priorities));
priorityOrder.addAll(availableItems);
String highestPriority = priorityOrder.poll();
Upvotes: 1
Reputation: 17299
Based on @Gilbert Le Blanc comment.
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));
Upvotes: 1