I'm new to programming and I'm trying to write a method which will choose the best option in a list. Here is what I've got:
item_no item_type origin
10 2 US
10 2 FR
10 4 UK
11 6 FR
I put these in a list:
[[10, 2, US], [10, 2, FR], [10, 4, UK], [11, 6, FR]]
I will take this list in my method and I also have a specific item with some features. Let's choose my specific item as;
item_no item_type origin
10 4 GE
Now, what I want to do is if one of the items in the list has a higher priority than my item, I will update my item's features with the higher priority item's features. The priority logic is respectively depends on item_code
, item_type
and origin
. To get the priority order I'm using maps like below:
HashMap<String, Integer> itemCodeOrder = x.getItemCodeOrder();
HashMap<String, Integer> itemTypeOrder = y.getItemTypeOrder();
HashMap<String, Integer> originOrder = z.getOriginOrder()
A typical priority order is like this:
In the first place I want to choose the higher priority item in the list and than compare that item with my item to update or not. For example, in the list above item_no 10
has higher priority than 11
, so I will chose one of the items which has the item_no 10
. Then, I will look at the item_type
: I have 2
and 4
, now I'll choose one of the the item with 2
. So after looking the origin
, I'll get [10, 2, US]
in the end I'll compare it with my item and update is like:
item_no item_type origin
10 2 US
I want to write a generic code but I couldn't find a proper way to get prior item in the list with my HashMap
logic. How I can handle with this?
First, create a comparator, which would compare first by code
, then by type
, and finally by origin
:
Comparator<Item> comparator = new Comparator<Item>() {
Map<String, Integer> codes = x.getItemCodeOrder();
Map<String, Integer> types = y.getItemTypeOrder();
Map<String, Integer> origins = z.getOriginOrder();
@Override
public int compare(Item a, Item b) {
int byCode = Objects.requireNonNull(codes.get(a.code))
.compareTo(Objects.requireNonNull(codes.get(b.code)));
if (byCode == 0) {
int byType = Objects.requireNonNull(types.get(a.type))
.compareTo(Objects.requireNonNull(types.get(b.type)));
if (byType == 0) {
return Objects.requireNonNull(origins.get(a.origin))
.compareTo(Objects.requireNonNull(origins.get(b.origin)));
} else
return byType;
} else
return byCode;
}
};
Then, sort your list of items:
Collections.sort(items, comparator);
The latest item in the list is now of the highest priority.
P.S. If you perform null-check on all list items before sorting, Objects.requiresNonNull()
wrapping can be easily omitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With