• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

Why entries are not sorted?

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why is the below code giving error?

Error:
prog.java:18: error: incompatible types: incompatible parameter types in lambda expression
      map.entrySet().stream().sorted((Map.Entry e)->e.comparingByKey()).forEach(e->System.out.println(e.getKey()+","+e.getValue()));

 
Saloon Keeper
Posts: 8704
71
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I merged your stuff with the following thread. I hope that is okay by you.
 
J Mohandos
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

My question is why all the entries are not sorted?

Output:
1,one
2,two
3,three
4,four
---------
1,one
2,two
3,three
4,four

 
Saloon Keeper
Posts: 13366
295
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are sorting the entries of the first map, and then you put them in a new map with Collectors.toMap(). This collector uses a HashMap by default, which won't maintain the ordering of your entries.

Tell toMap() to use a LinkedHashMap so it maintains insertion order:

Note that the map will no longer be sorted when you add new elements to it.

In general, trying to keep a map sorted by value is asking for trouble. Instead, just sort the elements right before you print them:
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic