Sort Map by Value
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MapSort {
public static void main(String[] args) {
Map<Integer, Employee> map = new HashMap<Integer, Employee>();
map.put(1, new Employee(1, "B"));
map.put(2, new Employee(1, "C"));
map.put(3, new Employee(1, "D"));
map.put(4, new Employee(1, "A"));
map.put(5, new Employee(1, "B"));
final Map<Integer, Employee> map1 = sortMapByValueInJava7(map);
map1.entrySet().stream().forEach(n -> {
System.out.println(n.getKey() + " : " + n.getValue().getName());
});
}
private static Map<Integer, Employee> sortMapByValueInJava7(Map<Integer, Employee> map) {
List<Map.Entry<Integer, Employee>> list = new ArrayList<Map.Entry<Integer, Employee>>(map.entrySet());
Collections.sort(list, (t1, t2) -> {
return t1.getValue().getName().compareTo(t2.getValue().getName());
});
final Map<Integer, Employee> map1 = new LinkedHashMap<Integer, Employee>();
list.stream().forEach(n -> {
map1.put(n.getKey(), n.getValue());
});
return map1;
}
}
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MapSort {
public static void main(String[] args) {
Map<Integer, Employee> map = new HashMap<Integer, Employee>();
map.put(1, new Employee(1, "B"));
map.put(2, new Employee(1, "C"));
map.put(3, new Employee(1, "D"));
map.put(4, new Employee(1, "A"));
map.put(5, new Employee(1, "B"));
final Map<Integer, Employee> map1 = sortMapByValueInJava7(map);
map1.entrySet().stream().forEach(n -> {
System.out.println(n.getKey() + " : " + n.getValue().getName());
});
}
private static Map<Integer, Employee> sortMapByValueInJava7(Map<Integer, Employee> map) {
List<Map.Entry<Integer, Employee>> list = new ArrayList<Map.Entry<Integer, Employee>>(map.entrySet());
Collections.sort(list, (t1, t2) -> {
return t1.getValue().getName().compareTo(t2.getValue().getName());
});
final Map<Integer, Employee> map1 = new LinkedHashMap<Integer, Employee>();
list.stream().forEach(n -> {
map1.put(n.getKey(), n.getValue());
});
return map1;
}
}
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Comments
Post a Comment