-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharraySort.java
More file actions
55 lines (46 loc) · 1.46 KB
/
arraySort.java
File metadata and controls
55 lines (46 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**Given an array of integers,
* write some code to find all the integers that appear more than once in the array,
* sorted by which appears most often to least often (once)
*/
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
class arraySort {
public static void main(String[] args){
int array[] = {1,1,1,1,46,46,35,57,1,68,23,68,68,68,136,35};
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> outputMap = new HashMap<Integer, Integer>();
System.out.println("The numbers in the array are:");
int i;
for(i = 0; i < array.length; i++) {
int number = array[i];
System.out.print(array[i] + " ");
Integer freq = map.get(number);
if (freq == null) {
map.put(number, 1);
}
else {
map.put(number, freq + 1);
outputMap.put(number, freq + 1);
}
}
System.out.println();
sortByValue(outputMap);
}
public static void sortByValue(Map<Integer, Integer> map) {
List<Map.Entry> list = new ArrayList<Map.Entry>(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o2, Object o1) {
Map.Entry e1 = (Map.Entry) o1;
Map.Entry e2 = (Map.Entry) o2;
return ((Comparable) e1.getValue()).compareTo(e2.getValue());
}
});
for (Map.Entry e : list) {
System.out.println(e.getKey() + " appears " + e.getValue() + " times");
}
}
}