Skip to content

Instantly share code, notes, and snippets.

@scolton99
Created May 24, 2021 22:02
Show Gist options
  • Select an option

  • Save scolton99/3d4ba6a2d12af78e2ff15de385b9fe2a to your computer and use it in GitHub Desktop.

Select an option

Save scolton99/3d4ba6a2d12af78e2ff15de385b9fe2a to your computer and use it in GitHub Desktop.
My solution to the Item Frequency problem.
package tech.scolton.jordan;
import java.util.*;
public class TechInterviewDriver {
public static void main(String[] args) {
String[] input = new String[]{"apple", "apple", "orange"};
Map<String, Integer> itemFreq = new HashMap<>();
for (String s : input) {
itemFreq.putIfAbsent(s, 0);
itemFreq.put(s, itemFreq.get(s) + 1);
}
List<Map.Entry<String, Integer>> entries = new ArrayList<>(itemFreq.entrySet());
entries.sort((x, y) -> y.getValue().compareTo(x.getValue()));
for (Map.Entry<String, Integer> entry : entries)
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment