title: Java 8 Stream - Map - sort by value
body: <p>Here is my data set.</p>
  
  <pre><code>public class StudentData {
  
      public static List&lt;Student&gt; getData() {
          //student id,name,std, and hobbies
          return Arrays.asList(new Student(1, "a1", 1, Arrays.asList("cricket", "football", "basketball")),
                  new Student(2, "a2", 1, Arrays.asList("chess", "football")),
                  new Student(3, "a3", 2, Arrays.asList("running")),
                  new Student(4, "a4", 2, Arrays.asList("throwball", "football")),
                  new Student(5, "a5", 3, Arrays.asList("cricket", "basketball")),
                  new Student(6, "a6", 4, Arrays.asList("cricket")), new Student(7, "a7", 5, Arrays.asList("basketball")),
                  new Student(8, "a8", 6, Arrays.asList("football")),
                  new Student(9, "a9", 8, Arrays.asList("tennis", "swimming")),
                  new Student(10, "a10", 8, Arrays.asList("boxing", "running")),
                  new Student(11, "a11", 9, Arrays.asList("cricket", "football")),
                  new Student(12, "a12", 11, Arrays.asList("tennis", "shuttle")),
                  new Student(13, "a13", 12, Arrays.asList("swimming")));
      }
  
  }
  </code></pre>
  
  <p>From data set , i am finding , how many student based on hobbies and display the value in asc/desc order. For example : cricket ,4 and swimming: 2 and so on.<br>
  here is the code for group by hoppies .</p>
  
  <pre><code>Map&lt;String, Integer&gt; collect8 = data.stream()
                  .flatMap(x -&gt; x.getHobbies().stream().map(y -&gt; new SimpleEntry&lt;&gt;(y, x)))
                  .collect(Collectors.groupingBy(Entry::getKey, Collectors.mapping(entry -&gt; entry.getValue().getId(),
                          Collectors.reducing(0, (a, b) -&gt; a + b))));
  </code></pre>
  
  <p>output of collect8  :{running=13, swimming=22, shuttle=12, throwball=4, basketball=13, chess=2, cricket=23, boxing=10, football=26, tennis=21}</p>
  
  <p>After that i am doing  asc sorting by value .</p>
  
  <pre><code>Map&lt;String, Integer&gt; collect9 = 
                  collect8.entrySet().stream().sorted(Map.Entry.&lt;String, Integer&gt;comparingByValue()).
                  collect(Collectors.toMap(e-&gt;e.getKey(), e-&gt;e.getValue()));
          System.out.println(collect9);
  </code></pre>
  
  <p>output of collect9 : {running=2, swimming=2, shuttle=1, throwball=1, basketball=3, chess=1, cricket=4, boxing=1, football=5, tennis=2}</p>
  
  <p>1.it is not sorted and giving the same result.any idea? <br />
  2. i am writing separate code for sorting. is it possble to do in collect8 itself?</p>