Java - Sort hashmap/TreeMap lexicographical Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Differences between HashMap and Hashtable?Is Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesHow do I read / convert an InputStream into a String in Java?How do I sort a dictionary by value?Iterate through a HashMapSort array of objects by string property valueDifference between HashMap, LinkedHashMap and TreeMapCreating a memory leak with JavaWhy is it faster to process a sorted array than an unsorted array?
Declining "dulcis" in context
Denied boarding although I have proper visa and documentation. To whom should I make a complaint?
Can a new player join a group only when a new campaign starts?
For a new assistant professor in CS, how to build/manage a publication pipeline
Fantasy story; one type of magic grows in power with use, but the more powerful they are, they more they are drawn to travel to their source
Significance of Cersei's obsession with elephants?
What is the escape velocity of a neutron particle (not neutron star)
Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?
Why do we bend a book to keep it straight?
Using et al. for a last / senior author rather than for a first author
Can melee weapons be used to deliver Contact Poisons?
How to tell that you are a giant?
Is there a kind of relay only consumes power when switching?
Is it cost-effective to upgrade an old-ish Giant Escape R3 commuter bike with entry-level branded parts (wheels, drivetrain)?
Trademark violation for app?
Do wooden building fires get hotter than 600°C?
What's the meaning of "fortified infraction restraint"?
Compare a given version number in the form major.minor.build.patch and see if one is less than the other
Crossing US/Canada Border for less than 24 hours
What causes the direction of lightning flashes?
Is safe to use va_start macro with this as parameter?
Fundamental Solution of the Pell Equation
Is there a holomorphic function on open unit disc with this property?
When a candle burns, why does the top of wick glow if bottom of flame is hottest?
Java - Sort hashmap/TreeMap lexicographical
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Differences between HashMap and Hashtable?Is Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesHow do I read / convert an InputStream into a String in Java?How do I sort a dictionary by value?Iterate through a HashMapSort array of objects by string property valueDifference between HashMap, LinkedHashMap and TreeMapCreating a memory leak with JavaWhy is it faster to process a sorted array than an unsorted array?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am practicing the use of hashmap and I would like to order my hashmap lexicographically. At this time, I have managed to do it with a list. This is the code of the list:
public class UsoUserlistaordenada
public static void inLista(ArrayList<User> l, User u ) throws Exception
// System.out.println(u.getName() +"/"+u.getShell());
for(User u1 : l)
int r = u1.getName().compareTo(u.getName());
if(r==0)
return;
if(r>0)
l.add(l.indexOf(u1),u);
return;
// System.out.println(u.getName() +"/"+u.getShell());
l.add(u);
return;
public static void main(String[] args) throws Exception
String line = null;
ArrayList<User> lista = new ArrayList<User>();
try (BufferedReader br = new BufferedReader(new FileReader("file")))
while ((line = br.readLine()) != null)
String[] parts = line.split(":");
String nombre_us = parts[0];
String id_grupo = parts[3];
String shell = parts[6];
User u = new User(nombre_us,id_grupo,shell);
inLista(lista,u);
//System.out.println(u.getName() +"/"+u.getShell());
int index=0;
for(User s : lista)
System.out.println(String.valueOf(index++)+": "+s);
catch (Exception ex)
ex.printStackTrace();
I would like to do it but with a hashmap. In this case, I would like to make the one with the least value have the key 0 and so on. Can you help me?
java sorting hashmap treemap
add a comment |
I am practicing the use of hashmap and I would like to order my hashmap lexicographically. At this time, I have managed to do it with a list. This is the code of the list:
public class UsoUserlistaordenada
public static void inLista(ArrayList<User> l, User u ) throws Exception
// System.out.println(u.getName() +"/"+u.getShell());
for(User u1 : l)
int r = u1.getName().compareTo(u.getName());
if(r==0)
return;
if(r>0)
l.add(l.indexOf(u1),u);
return;
// System.out.println(u.getName() +"/"+u.getShell());
l.add(u);
return;
public static void main(String[] args) throws Exception
String line = null;
ArrayList<User> lista = new ArrayList<User>();
try (BufferedReader br = new BufferedReader(new FileReader("file")))
while ((line = br.readLine()) != null)
String[] parts = line.split(":");
String nombre_us = parts[0];
String id_grupo = parts[3];
String shell = parts[6];
User u = new User(nombre_us,id_grupo,shell);
inLista(lista,u);
//System.out.println(u.getName() +"/"+u.getShell());
int index=0;
for(User s : lista)
System.out.println(String.valueOf(index++)+": "+s);
catch (Exception ex)
ex.printStackTrace();
I would like to do it but with a hashmap. In this case, I would like to make the one with the least value have the key 0 and so on. Can you help me?
java sorting hashmap treemap
3
I would like to do it but with a hashmap - you can't. Hashmap don't guarantee that the insertion order is kept. However, you could use aTreeMap
– BackSlash
Mar 22 at 9:41
I did not know that, can you provide a code using a 'treemap' in that case? It would help me a lot
– UsuarioConMiga
Mar 22 at 9:43
1
Just replace yourHashMapwithTreeMapand you're done, no need to do anything more fancy
– Lino
Mar 22 at 9:47
add a comment |
I am practicing the use of hashmap and I would like to order my hashmap lexicographically. At this time, I have managed to do it with a list. This is the code of the list:
public class UsoUserlistaordenada
public static void inLista(ArrayList<User> l, User u ) throws Exception
// System.out.println(u.getName() +"/"+u.getShell());
for(User u1 : l)
int r = u1.getName().compareTo(u.getName());
if(r==0)
return;
if(r>0)
l.add(l.indexOf(u1),u);
return;
// System.out.println(u.getName() +"/"+u.getShell());
l.add(u);
return;
public static void main(String[] args) throws Exception
String line = null;
ArrayList<User> lista = new ArrayList<User>();
try (BufferedReader br = new BufferedReader(new FileReader("file")))
while ((line = br.readLine()) != null)
String[] parts = line.split(":");
String nombre_us = parts[0];
String id_grupo = parts[3];
String shell = parts[6];
User u = new User(nombre_us,id_grupo,shell);
inLista(lista,u);
//System.out.println(u.getName() +"/"+u.getShell());
int index=0;
for(User s : lista)
System.out.println(String.valueOf(index++)+": "+s);
catch (Exception ex)
ex.printStackTrace();
I would like to do it but with a hashmap. In this case, I would like to make the one with the least value have the key 0 and so on. Can you help me?
java sorting hashmap treemap
I am practicing the use of hashmap and I would like to order my hashmap lexicographically. At this time, I have managed to do it with a list. This is the code of the list:
public class UsoUserlistaordenada
public static void inLista(ArrayList<User> l, User u ) throws Exception
// System.out.println(u.getName() +"/"+u.getShell());
for(User u1 : l)
int r = u1.getName().compareTo(u.getName());
if(r==0)
return;
if(r>0)
l.add(l.indexOf(u1),u);
return;
// System.out.println(u.getName() +"/"+u.getShell());
l.add(u);
return;
public static void main(String[] args) throws Exception
String line = null;
ArrayList<User> lista = new ArrayList<User>();
try (BufferedReader br = new BufferedReader(new FileReader("file")))
while ((line = br.readLine()) != null)
String[] parts = line.split(":");
String nombre_us = parts[0];
String id_grupo = parts[3];
String shell = parts[6];
User u = new User(nombre_us,id_grupo,shell);
inLista(lista,u);
//System.out.println(u.getName() +"/"+u.getShell());
int index=0;
for(User s : lista)
System.out.println(String.valueOf(index++)+": "+s);
catch (Exception ex)
ex.printStackTrace();
I would like to do it but with a hashmap. In this case, I would like to make the one with the least value have the key 0 and so on. Can you help me?
java sorting hashmap treemap
java sorting hashmap treemap
edited Mar 22 at 11:02
user207421
264k26216365
264k26216365
asked Mar 22 at 9:40
UsuarioConMigaUsuarioConMiga
335
335
3
I would like to do it but with a hashmap - you can't. Hashmap don't guarantee that the insertion order is kept. However, you could use aTreeMap
– BackSlash
Mar 22 at 9:41
I did not know that, can you provide a code using a 'treemap' in that case? It would help me a lot
– UsuarioConMiga
Mar 22 at 9:43
1
Just replace yourHashMapwithTreeMapand you're done, no need to do anything more fancy
– Lino
Mar 22 at 9:47
add a comment |
3
I would like to do it but with a hashmap - you can't. Hashmap don't guarantee that the insertion order is kept. However, you could use aTreeMap
– BackSlash
Mar 22 at 9:41
I did not know that, can you provide a code using a 'treemap' in that case? It would help me a lot
– UsuarioConMiga
Mar 22 at 9:43
1
Just replace yourHashMapwithTreeMapand you're done, no need to do anything more fancy
– Lino
Mar 22 at 9:47
3
3
I would like to do it but with a hashmap - you can't. Hashmap don't guarantee that the insertion order is kept. However, you could use a
TreeMap– BackSlash
Mar 22 at 9:41
I would like to do it but with a hashmap - you can't. Hashmap don't guarantee that the insertion order is kept. However, you could use a
TreeMap– BackSlash
Mar 22 at 9:41
I did not know that, can you provide a code using a 'treemap' in that case? It would help me a lot
– UsuarioConMiga
Mar 22 at 9:43
I did not know that, can you provide a code using a 'treemap' in that case? It would help me a lot
– UsuarioConMiga
Mar 22 at 9:43
1
1
Just replace your
HashMap with TreeMap and you're done, no need to do anything more fancy– Lino
Mar 22 at 9:47
Just replace your
HashMap with TreeMap and you're done, no need to do anything more fancy– Lino
Mar 22 at 9:47
add a comment |
1 Answer
1
active
oldest
votes
See HashMap vs TreeMap
HashMap doesn’t provide any guarantee over the way the elements are
arranged in the Map
Also i don't think that TreeMap is good solution for you. The sorting will be done by keys, not by values:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
int i = 0;
Map<Integer, String> map = new TreeMap<>();
for(String s: input)
map.put(i++, s);
System.out.println(map);
If the key is integer, why not use simple array or list?
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
List<String> list = new ArrayList<>(Arrays.asList(input));
list.sort(Comparator.naturalOrder());
System.out.println(list);
If you need sorting at the insertion time you could use TreeSet. It'll give you sorting and can be easily converted to array or list:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
Set<String> set = new TreeSet<>();
set.addAll(Arrays.asList(input));
System.out.println(set);
String[] array = set.toArray(new String[0]);
System.out.println(array[0]);
List<String> list = new ArrayList<>(set);
System.out.println(list.get(0));
The rest is comparator for sorting. You could use Comparator.comparing(User::getName) or implement the comparable interface.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55296743%2fjava-sort-hashmap-treemap-lexicographical%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
See HashMap vs TreeMap
HashMap doesn’t provide any guarantee over the way the elements are
arranged in the Map
Also i don't think that TreeMap is good solution for you. The sorting will be done by keys, not by values:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
int i = 0;
Map<Integer, String> map = new TreeMap<>();
for(String s: input)
map.put(i++, s);
System.out.println(map);
If the key is integer, why not use simple array or list?
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
List<String> list = new ArrayList<>(Arrays.asList(input));
list.sort(Comparator.naturalOrder());
System.out.println(list);
If you need sorting at the insertion time you could use TreeSet. It'll give you sorting and can be easily converted to array or list:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
Set<String> set = new TreeSet<>();
set.addAll(Arrays.asList(input));
System.out.println(set);
String[] array = set.toArray(new String[0]);
System.out.println(array[0]);
List<String> list = new ArrayList<>(set);
System.out.println(list.get(0));
The rest is comparator for sorting. You could use Comparator.comparing(User::getName) or implement the comparable interface.
add a comment |
See HashMap vs TreeMap
HashMap doesn’t provide any guarantee over the way the elements are
arranged in the Map
Also i don't think that TreeMap is good solution for you. The sorting will be done by keys, not by values:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
int i = 0;
Map<Integer, String> map = new TreeMap<>();
for(String s: input)
map.put(i++, s);
System.out.println(map);
If the key is integer, why not use simple array or list?
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
List<String> list = new ArrayList<>(Arrays.asList(input));
list.sort(Comparator.naturalOrder());
System.out.println(list);
If you need sorting at the insertion time you could use TreeSet. It'll give you sorting and can be easily converted to array or list:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
Set<String> set = new TreeSet<>();
set.addAll(Arrays.asList(input));
System.out.println(set);
String[] array = set.toArray(new String[0]);
System.out.println(array[0]);
List<String> list = new ArrayList<>(set);
System.out.println(list.get(0));
The rest is comparator for sorting. You could use Comparator.comparing(User::getName) or implement the comparable interface.
add a comment |
See HashMap vs TreeMap
HashMap doesn’t provide any guarantee over the way the elements are
arranged in the Map
Also i don't think that TreeMap is good solution for you. The sorting will be done by keys, not by values:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
int i = 0;
Map<Integer, String> map = new TreeMap<>();
for(String s: input)
map.put(i++, s);
System.out.println(map);
If the key is integer, why not use simple array or list?
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
List<String> list = new ArrayList<>(Arrays.asList(input));
list.sort(Comparator.naturalOrder());
System.out.println(list);
If you need sorting at the insertion time you could use TreeSet. It'll give you sorting and can be easily converted to array or list:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
Set<String> set = new TreeSet<>();
set.addAll(Arrays.asList(input));
System.out.println(set);
String[] array = set.toArray(new String[0]);
System.out.println(array[0]);
List<String> list = new ArrayList<>(set);
System.out.println(list.get(0));
The rest is comparator for sorting. You could use Comparator.comparing(User::getName) or implement the comparable interface.
See HashMap vs TreeMap
HashMap doesn’t provide any guarantee over the way the elements are
arranged in the Map
Also i don't think that TreeMap is good solution for you. The sorting will be done by keys, not by values:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
int i = 0;
Map<Integer, String> map = new TreeMap<>();
for(String s: input)
map.put(i++, s);
System.out.println(map);
If the key is integer, why not use simple array or list?
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
List<String> list = new ArrayList<>(Arrays.asList(input));
list.sort(Comparator.naturalOrder());
System.out.println(list);
If you need sorting at the insertion time you could use TreeSet. It'll give you sorting and can be easily converted to array or list:
public static void main(String args[])
String[] input = "a", "b", "f", "h", "e", "aa";
Set<String> set = new TreeSet<>();
set.addAll(Arrays.asList(input));
System.out.println(set);
String[] array = set.toArray(new String[0]);
System.out.println(array[0]);
List<String> list = new ArrayList<>(set);
System.out.println(list.get(0));
The rest is comparator for sorting. You could use Comparator.comparing(User::getName) or implement the comparable interface.
edited Mar 22 at 10:36
answered Mar 22 at 10:08
Mikhail IlinykhMikhail Ilinykh
623310
623310
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55296743%2fjava-sort-hashmap-treemap-lexicographical%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
I would like to do it but with a hashmap - you can't. Hashmap don't guarantee that the insertion order is kept. However, you could use a
TreeMap– BackSlash
Mar 22 at 9:41
I did not know that, can you provide a code using a 'treemap' in that case? It would help me a lot
– UsuarioConMiga
Mar 22 at 9:43
1
Just replace your
HashMapwithTreeMapand you're done, no need to do anything more fancy– Lino
Mar 22 at 9:47