Created
February 1, 2024 11:41
-
-
Save julianjupiter/1e20d86ec6d212793ada9996f932c240 to your computer and use it in GitHub Desktop.
Get fruits with highest count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class FruitsApp { | |
public static void main(String[] args) { | |
var fruits = new String[] { | |
"Apple", | |
"Banana", | |
"Cherry", | |
"Apple", | |
"Dragonfruit", | |
"Orange", | |
"Kiwi", | |
"Cherry", | |
"Orange", | |
"Apple", | |
"Kiwi", | |
"Dragonfruit", | |
"Dragonfruit", | |
"Kiwi" | |
}; | |
// put fruits in the map with count | |
var map = new HashMap<String, Integer>(); | |
for (var fruit : fruits) { | |
if (map.containsKey(fruit)) { | |
map.put(fruit, map.get(fruit) + 1); | |
} else { | |
map.put(fruit, 1); | |
} | |
} | |
System.out.println("Map\n" + map); | |
// get max count | |
int max = 0; | |
for (var fruit : map.entrySet()) { | |
var count = fruit.getValue(); | |
if (count > max) { | |
max = count; | |
} | |
} | |
System.out.println("Max: " + max); | |
// get all fruits with count equals to max | |
var list = new ArrayList<Map.Entry<String, Integer>>(); | |
for (var fruit : map.entrySet()) { | |
var count = fruit.getValue(); | |
if (count == max) { | |
list.add(fruit); | |
} | |
} | |
System.out.println("List:"); | |
for (var l : list) { | |
System.out.println(l.getKey() + " " + l.getValue()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Map | |
{Apple=3, Kiwi=3, Cherry=2, Dragonfruit=3, Orange=2, Banana=1} | |
Max: 3 | |
List: | |
Apple 3 | |
Kiwi 3 | |
Dragonfruit 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment