# How to sort hashMap by keys?

• (2 Pages)
• 1
• 2

## 19 Replies - 4824 Views - Last Post: 10 October 2013 - 03:43 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=330789&amp;s=f267dc9910232fcf7724c4e9745f88b1&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

# How to sort hashMap by keys?

Posted 05 October 2013 - 05:22 AM

Hi, I'm trying to sort hashmap by keys.
I have Map<Student, Integer> map = HashMap<>();

// Student(id, name, age) , postcode
map.put(new Student(1, "C", 22), 1048);
map.put(new Student(2, "A", 20), 2913);
map.put(new Student(6, "D", 20), 2013);
map.put(new Student(9, "B", 21), 2012); and so on.

Is there any ways that the map can be sorted by say, Student's name (alphabetical order)? so the output would be;
Student(2, "A", 20), 2913
Student(9, "B", 21), 2012
Student(1, "C", 22), 1048
Student(6, "D", 20), 2013

I first attempted to convert the keys into arrayList and sort them on the basis of Name, and build a new hashmap.
But, I've got no idea how to do it so...

Is This A Good Question/Topic? 0

## Replies To: How to sort hashMap by keys?

### #2 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 05 October 2013 - 05:43 AM

You can use a SortedMap with a Comparator:

```public class StudSort {
public static void main(String[] args) {
SortedMap<Student, Integer> map = new TreeMap<Student, Integer>(new StudentComparator());
// Student(id, name, age) , postcode
map.put(new Student(1, "C", 22), 1048);
map.put(new Student(2, "A", 20), 2913);
map.put(new Student(6, "D", 20), 2013);
map.put(new Student(9, "B", 21), 2012);
System.out.println(map);
}

private static class StudentComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName());
}
}
}

```

btw, postcodes are strings, not numbers (usually)

This post has been edited by g00se: 05 October 2013 - 05:45 AM
Reason for edit:: indent

### #3 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

## Re: How to sort hashMap by keys?

Posted 05 October 2013 - 09:17 PM

g00se, on 05 October 2013 - 05:43 AM, said:

You can use a SortedMap with a Comparator: .... btw, postcodes are strings, not numbers (usually)

Thank you very much for both coding and post code thing.

um.. I would like to ask one more similar question about the sorting.
I saw many options to sort things not only sortby names but also other attributes such as id, age etc. so I've decided to implement a function for "ID-sort" as well.
But I ended up getting the same approach I took earlier.

```import java.util.Comparator;

public class Student implements Comparable<Student> /**, Comparator<Student>*/{
private static int id; // why do I need id to be "static?"
private String name;
private static int age;
public Student(int i, String n, int a){
id=i;
name=n;
age=a;
}

public int getID(){
return id;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}

// this is for sorting by name
@Override
public int compareTo(Student o) {
return name.compareTo(o.getName());
}
// this is for sorting by id
public static Comparable<Student> idOrder = new Comparable<Student>() {
@Override
public int compareTo(Student o) {
return ((Integer)id).compareTo(o.getID());
}
};
// this is for sorting by age
public static Comparable<Student> ageOrder = new Comparable<Student>() {
@Override
public int compareTo(Student o) {
return ((Integer)age).compareTo(o.getAge());
}
};
/** seems only works for array/list?
// this is for sorting by name : Comparator
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}

// this is for sorting by id
public static Comparator<Student> idOrder = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return ((Integer)o1.getID()).compareTo(o2.getID());
}
};
// this is for sorting by age
public static Comparator<Student> ageOrder = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return ((Integer)o1.getAge()).compareTo(o2.getAge());
}
};
*/
}

```

```import java.util.Collections;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class StudentSet {
SortedMap<Student, String> studentSet;

public StudentSet() {
studentSet = new TreeMap<>();
}
public void intput(Student s, String str){
studentSet.put(s, str);
}

//------------------------------------------
// sort the set on the basis of Name.
public Map<Student, String> getNameSet() {
return studentSet;
}
// sort the set on the basis of ID.
public SortedMap<Student, String> getIDSet() {
// do something .. somehow need to use idOrder in Student
//Collections.sort(studentSet, Student.idOrder);
return studentSet;
}
// sort the set on the basis of AGE.
public SortedMap<Student, String> getAgeSet() {
// do something .. somehow need to use ageOrder in Student
return studentSet;
}
}

```

```public class Tester {
public static void main(String[] args){
StudentSet map = new StudentSet();
// Student(id, name, age) , post code
map.intput(new Student(1, "C", 22), "1048");
map.intput(new Student(2, "A", 20), "2913");
map.intput(new Student(6, "D", 20), "2013");
map.intput(new Student(9, "B", 21), "2012");

// Name : alphabetical order
for (Student s : map.getNameSet().keySet()){
System.out.println(s.getName()+":"+map.getNameSet().get(s));
}
System.out.println("---------ID");
// ID order
for (Student s : map.getIDSet().keySet()){
System.out.println(s.getID()+":"+map.getIDSet().get(s));
}
System.out.println("---------AGE");
// Age order
for (Student s : map.getAgeSet().keySet()){
System.out.println(s.getAge()+":"+map.getAgeSet().get(s));
}
}
}

```

### #4 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 06 October 2013 - 01:41 AM

Quote

But I ended up getting the same approach I took earlier.
Why? All you need is to implement a different Comparator for age and for id. Create a new TreeMap with the correct Comparator and fill it from the original Map

### #5 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

## Re: How to sort hashMap by keys?

Posted 06 October 2013 - 10:47 PM

g00se, on 06 October 2013 - 01:41 AM, said:

Quote

But I ended up getting the same approach I took earlier.
Why? All you need is to implement a different Comparator for age and for id. Create a new TreeMap with the correct Comparator and fill it from the original Map

I deleted "Comparable<Student> idOrder" and "Comparable<Student> ageOrder" and
enabled these "Comparator<Student> idOrder" and "Comparator<Student> ageOrder" in Student class
``` // this is for sorting by id
public static Comparator<Student> idOrder = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return ((Integer)o1.getID()).compareTo(o2.getID());
}
};
// this is for sorting by age
public static Comparator<Student> ageOrder = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return ((Integer)o1.getAge()).compareTo(o2.getAge());
}
};

```

and in Student class I modified a getIDSet() method like this;
```SortedMap<Student, String> sortedMap = new TreeMap<>(Student.idOrder);
sortedMap.putAll(studentSet);
return sortedMap;

```

and somewhat I only got an output "9:A:21:2013" using
```// ID order
for (Student s : map.getIDSet().keySet()){
System.out.println(s.getID()+":"+s.getName()+":"+s.getAge()+":"+map.getIDSet().get(s));
}

```

in Tester.
There are two things I don't get.
1: why "sortedMap.putAll(studentSet);" in StudentSet does not put all the components of "studentSet" into "sortedMap".
2: why has the elements of the key changed? Isn't is supposed to be "9:"B":21:2012"? if Student whose id is 9 is to be printed.

### #6 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 01:45 AM

Quote

```for (Student s : map.getIDSet().keySet()){
```

Not sure what getIDSet() is meant to do but you can use the generic

```Set<Student> studentKeys = map.keySet();
for(Student s : studentKeys) {
System.out.printf("Id is %d%n", s.getId());
}

```

This should show the correct order (if you used the correct Map)

This post has been edited by g00se: 07 October 2013 - 01:45 AM
Reason for edit:: code

### #7 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 02:50 AM

g00se, on 07 October 2013 - 01:45 AM, said:

Quote

```for (Student s : map.getIDSet().keySet()){
```

Not sure what getIDSet() is meant to do but you can use the generic

```Set<Student> studentKeys = map.keySet();
for(Student s : studentKeys) {
System.out.printf("Id is %d%n", s.getId());
}

```

This should show the correct order (if you used the correct Map)
"
The method getIDSet() returns "Map<Student, String>" for ,keySet() in Tester class above.
I think there is nothing wrong with displaying all elements of the map.

The problem I can't figure out is that why the output is not showing 4 elements of the map.

First of all, these elements are put in to "SortedMap<Student, String> studentSet;" which is in StudentSet class.
StudentSet map = new StudentSet();
// Student(id, name, age) , post code
map.intput(new Student(1, "C", 22), "1048");
map.intput(new Student(2, "A", 20), "2913");
map.intput(new Student(6, "D", 20), "2013");
map.intput(new Student(9, "B", 21), "2012");

and then, I did this based on

Quote

Create a new TreeMap with the correct Comparator and fill it from the original Map

``` // sort the set on the basis of ID.
public Map<Student, String> getIDSet() {
SortedMap<Student, String> sortedMap = new TreeMap<>(Student.idOrder);
sortedMap.putAll(studentSet);
return sortedMap;
}

```

Here, I think the sortedMap should have 4 elements but it only has "1" element which is "9:"B":21:2012".
Is there anything wrong with filling the sortedMap?

### #8 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 03:01 AM

First of all, let's get our terminology right or it will get confusing. A Map doesn't have elements, it has entries

Quote

```sortedMap.putAll(studentSet);
```

'studentSet' must be of type Map - is it? It sure doesn't sound as if it is by its name ...

### #9 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 03:45 AM

g00se, on 07 October 2013 - 03:01 AM, said:

First of all, let's get our terminology right or it will get confusing. A Map doesn't have elements, it has entries

Quote

```sortedMap.putAll(studentSet);
```

'studentSet' must be of type Map - is it? It sure doesn't sound as if it is by its name ...

I see. I change 'studentSet' to `studentMap` now.

### #10 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 03:51 AM

I don't see any reason for there being one entry other than there being only one entry in the source Map

### #11 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 04:15 AM

well, my assumption was that because 4 entries were put in the source Map, there should also be 4 entries copied to the new map.

### #12 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 04:58 AM

Correct. Print the source Map before and then the target Map

### #13 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 03:29 PM

What if two students have the same postal code ?

### #14 pineapplePie

Reputation: 0
• Posts: 69
• Joined: 23-January 12

## Re: How to sort hashMap by keys?

Posted 07 October 2013 - 06:12 PM

g00se, on 07 October 2013 - 04:58 AM, said:

Correct. Print the source Map before and then the target Map

I have been doing it but the results are the same. It only displays "9:"B":21:2012".
Top of that, if I delete "Student.idOrder" from SortedMap<Student, String> sortedMap = new TreeMap<>(Student.idOrder);,
even though I can see there are 4 entries in the sortedMap, there are all "9:"B":21:2012".

pbl, on 07 October 2013 - 03:29 PM, said:

What if two students have the same postal code ?

I assume the the entries would be ordered on the basis of id. so if there are

Student(9, "P", 20), "2913"
Student(1, "C", 22), "2913"
Student(5, "A", 19), "2913"

then the output should be like

Student(1, "C", 22), "2913"
Student(5, "A", 19), "2913"
Student(9, "P", 20), "2913"

### #15 g00se

• D.I.C Lover

Reputation: 3540
• Posts: 16,130
• Joined: 20-September 08

## Re: How to sort hashMap by keys?

Posted 08 October 2013 - 02:18 AM