I am trying to write a function that takes a map and returns a record. If the record with the maximum value of Integer is unique, it should return this record. However, if there are duplicate records with the same maximum value, it should return a new record with the "MULTIPLE" key and a value of 0. It’s easy enough for me to get the maximum value, ignoring duplicates:
public static Entry<String,Integer> getMax(Map<String,Integer> map1) {
return map1.entrySet().stream()
.max((a,b) -> a.getValue().compareTo(b.getValue()))
.get();
}
But in order for me to do what I said at first, I could find a solution where I needed to create an initial thread in order to perform a logical check if there were several maximum values, and then make another thread if I did not get the value. I would like to find a solution where I can perform both tasks with only one thread.
Here is my little test case:
@Test
public void test1() {
Map<String,Integer> map1 = new HashMap<>();
map1.put("A", 100);
map1.put("B", 100);
map1.put("C", 100);
map1.put("D", 105);
Assert.assertEquals("D", getMax(map1).getKey());
Map<String,Integer> map2 = new HashMap<>();
map2.put("A", 100);
map2.put("B", 105);
map2.put("C", 100);
map2.put("D", 105);
Assert.assertEquals("MULTIPLE", getMax(map2).getKey());
wlaem source
share