Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Created February 1, 2024 11:41
Show Gist options
  • Save julianjupiter/1e20d86ec6d212793ada9996f932c240 to your computer and use it in GitHub Desktop.
Save julianjupiter/1e20d86ec6d212793ada9996f932c240 to your computer and use it in GitHub Desktop.
Get fruits with highest count
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());
}
}
}
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