-3

I have read about it on the forums but with many solutions available none of them seemed to work for me, i have an array list that is being filled as the program runs and at the end i want to find which string element occurred the most and simply print out which one it was. I have seen some solutions using maps and comparator but i dont know how to make them work, as they were used more for an array rather than array list and i dont know how to adapt it to mine.

The code I have:

static ArrayList<String> sequence = new ArrayList<String>();

////////////////////// ARRAY LIST ////////////////////////////////

    public static void PrintArray(){
        System.out.println("The Movement sequence is:  " + sequence);

    }

    public static void FindMostCommon(){

    }

elements are added in different parts of the code with ;

sequence.add("MoveLeft() ");

I need a simple way to find the most common occurring one from that list, preferably using the function i created; FindMostCommon();

Also an explaination of what is going on in the code would be appreciated :)

Bart123
  • 45
  • 2
  • 11
  • The only thing holding you back is the difference between coding for an array vs. a list? I'd recommend trying a bit harder before coming back with a specific question when you have a genuine issue beyond "I don't know what to do". Iterating over a list is trivial, and all you need to do is drop them into a map of strings to counts, then get the highest count (which you could even do as you iterated). – Dave Newton Mar 06 '17 at 15:39

2 Answers2

2

Fill a Map with the unique Strings in your ArrayList and count their occurrences

Map<String,Long> counts = sequence.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));

Get the key corresponding to the max occurrence count

String s = counts.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
Robin Topper
  • 2,295
  • 1
  • 17
  • 25
1

You can start with mapping the strings to their occurence:

Map<String, Integer> countPerString = new HashMap<String, Integer>();
sequence.forEach(s -> countPerString.put(s, countPerString.getOrDefault(s, 0) + 1));

Then you only have to find the key with the highest count:

    String max = countPerString.keySet().stream().reduce((s1, s2) -> {
        if (countPerString.get(s1) > countPerString.get(s2)) {
            return s1;
        }
        return s2;
    }).orElseThrow(() -> new IllegalStateException("no max found"));
thopaw
  • 3,796
  • 2
  • 17
  • 24