Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. public class ArrayTask {
  2.     public static void main(String[] args) {
  3.         int[] sequence = {1, 3, 1, 3, 2, 1, 3, 4, 4, 4};
  4.         System.out.println(getMostFrequent(sequence));
  5.     }
  6.  
  7.     public static Set getMostFrequent(int[] givenArray) {
  8.         List<Integer> listGivenArray = Arrays.stream(givenArray).boxed().collect(Collectors.toList());
  9.         Map<Integer, Integer> map = new HashMap<>();
  10.  
  11.         for (int i = 0; i < listGivenArray.size(); i++) {
  12.             int k = 0;
  13.             for (int j = 0; j < listGivenArray.size(); j++) {
  14.                 if (listGivenArray.get(i) == listGivenArray.get(j)) {
  15.                     k++;
  16.                     map.put(listGivenArray.get(i), k);
  17.                 }
  18.             }
  19.         }
  20.         Set listOfMatches = new HashSet();
  21.         Map.Entry<Integer, Integer> maxEntry = null;
  22.  
  23.         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
  24.            if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
  25.                 maxEntry = entry;
  26.                listOfMatches.add(maxEntry);
  27.             }
  28.             if ((maxEntry != null && entry.getValue().compareTo(maxEntry.getValue()) == 0)) {
  29.                 listOfMatches.add(entry);
  30.             }
  31.         }
  32.         return listOfMatches;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement