Java ArrayList Sort sortedPatterns(ArrayList patterns)

Here you can find the source of sortedPatterns(ArrayList patterns)

Description

sorted Patterns

License

Open Source License

Declaration

public static String sortedPatterns(ArrayList<String> patterns) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {
    public static String sortedPatterns(ArrayList<String> patterns) {

        Map<String, Integer> wordCount = new HashMap<String, Integer>();

        Set<String> unique = new HashSet<String>(patterns);
        for (String key : unique) {
            wordCount.put(key, Collections.frequency(patterns, key));
        }//from   w  ww . j  a va  2  s  .  c o m

        // Convert map to list of <String,Integer> entries
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
                wordCount.entrySet());

        // Sort list by integer values
        Collections.sort(list,
                new Comparator<Map.Entry<String, Integer>>() {
                    public int compare(Map.Entry<String, Integer> o1,
                            Map.Entry<String, Integer> o2) {
                        // compare o2 to o1, instead of o1 to o2, to get descending freq. order
                        return (o2.getValue()).compareTo(o1.getValue());
                    }
                });

        // Create the result String
        String result = "";
        for (Map.Entry<String, Integer> entry : list) {
            result += (entry.getKey() + ", ");
        }
        // Omit last ', ' substring
        return result.substring(0, result.length() - 2);

    }
}

Related

  1. sortArray(ArrayList list)
  2. sortByNibble(ArrayList symbolAL, int delimiter)
  3. sortImports(ArrayList imports)
  4. sortSignatures(ArrayList sList)
  5. SortStringList(ArrayList list)