3

I am currently trying to use a LinkedList to print a list of keys from their highest number of occurences to lowest. I am trying to use the sort method on the getValue method of the entry but it is not working. Any ideas what I'm doing wrong. Here is a snippet of my code

// Beginning tree map
        Map<String, Integer> map1 = new TreeMap<>();
        String[] words1 = text.split("[ \n\t\r.,;:!?(){ ]");
        for (int i = 0; i < words1.length; i++) 
        {
            String key = words1[i].toLowerCase();

            if (key.length() > 0) 
            {
                if (!map1.containsKey(key)) 
                {
                    map1.put(key, 1);
                }
                else 
                {
                    int value = map1.get(key);
                    value++;
                    map1.put(key, value);
                }
            }
        }
        Set<Map.Entry<String, Integer>> entrySet1 = map1.entrySet();
        // Get key and value from each entry
        System.out.println("Treemap: " + map1);
        for (Map.Entry<String, Integer> entry: entrySet1)
            System.out.println(entry.getValue() + "\t" + entry.getKey());
        System.out.println("");
        // Beginning for LinkedList
        LinkedList<Entry<String, Integer>> linkedList = new LinkedList<>(entrySet1);
        System.out.println("linkedList:");
        System.out.println(linkedList);
        System.out.println(linkedList.sort(entrySet1.getKey());

With my current output

Treemap: {a=2, class=1, fun=1, good=3, have=3, morning=1, visit=1}
2   a
1   class
1   fun
3   good
3   have
1   morning
1   visit

linkedList:
[a=2, class=1, fun=1, good=3, have=3, morning=1, visit=1]

So my ultimate question is, how can i pass my getValue method to the LinkedList in order to print them in a sorted order.

Arun Shankar
  • 2,603
  • 2
  • 26
  • 36
john woolstock
  • 177
  • 1
  • 7
  • You can look at how the built in sort for LinkedList works. Note: the fastest way to do this is to copy the elements to an array, quick sort it and copy the elements back when done. – Peter Lawrey Oct 29 '15 at 17:41
  • try this it will help you http://stackoverflow.com/questions/16425127/how-to-use-collections-sort-in-java-specific-situation – RamPrakash Oct 29 '15 at 17:42
  • I'm not familiar with Java 8 so perhaps I'm missing something, but it looks to me like the code shouldn't compile. It's calling `getKey()` on `entrySet1`, which is a `Set`, but `Set` [doesn't have a getKey() method](http://docs.oracle.com/javase/8/docs/api/java/util/Set.html). Also one of the last two `println()` statements is not reflected in the output. – elhefe Apr 08 '16 at 04:32

0 Answers0