Java Streaming: get max if no duplicates

Viewed 429

I'm trying to write a function that takes in a Map and returns an Entry. If the entry with the max Integer value is unique, it should return that entry. However, if there are duplicate entries with the same max value, it should return a new Entry with a key of "MULTIPLE" and a value of 0. It's easy enough for me to get the max 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 initially, I could only find a solution where I had to create an initial stream to do a boolean check if there were multiple max values and then do another stream if not to get the value. I'd like to find a solution where I can do both tasks with only one stream.

Here's 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());
2 Answers
Related