Tony
Tony

Reputation: 37

How to sort this Map<String, List<class>>

I have this Map, which contains names, last names, and other personal information , for exmaple:

jhon:[doe];

ann:[devil]

What I want is to order them alphabetically, but this kind of structure is new to me. How can I order them alphabetically? Here my code

 private String uid;
    private String username;
    private String fullName;
    private String name;
    private String lastname;
    private String email;
    private String phone;
    private Map<String, List<PorticoProfile>> profiles;

    public Map<String, List<PorticoProfile>> getProfiles() {
        if (profiles == null) {
            profiles = new LinkedHashMap<>();
        }
        return profiles;
    }

    public void setProfiles(Map<String, List<PorticoProfile>> profiles) {
        this.profiles = profiles;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
        if (fullName.contains(" ")){
            String[] nameParts = fullName.split(" ");
            this.name = nameParts[0];
            this.lastname = nameParts[1];
        }
    }

    @Override
    public String toString(){
        final String BREAK = System.getProperty("line.separator");
        StringBuilder sb = new StringBuilder();
        sb.append("uid: ").append(this.uid).append(BREAK);
        sb.append("username: ").append(this.username).append(BREAK);
        sb.append("fullname: ").append(this.fullName).append(BREAK);
        sb.append("email: ").append(this.email).append(BREAK);
        sb.append("phone: ").append(this.phone).append(BREAK);
        if (this.getProfiles().size() > 0){
            sb.append("profiles: ").append(this.profiles.keySet().stream().collect(Collectors.joining(", "))).append(BREAK);
        }
        return sb.toString();
    }

Upvotes: 1

Views: 95

Answers (3)

xingbin
xingbin

Reputation: 28289

Try:

Map<String, List<MyClass>> sorted = map.entrySet()
        .stream()
        .sorted(Comparator.comparing(Map.Entry::getKey)) // sort by key
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Upvotes: 1

Rishikesh Dhokare
Rishikesh Dhokare

Reputation: 3589

Use TreeMap - https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

LinkedHashMap will preserve the order in which you add data to the Map, TreeMap will keep it sorted based on the key, which in your case is String i.e. the name

Map<String, List<PorticoProfile>> profiles = new TreeMap<>();;

Upvotes: 1

Friso
Friso

Reputation: 1110

I think you should checkout another interface: the SortedMap (https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html)

    Map<String, Object> m = new HashMap<>();
    m.put("john", "doe");
    m.put("ann", "devil");

    SortedMap<String, Object> s = new TreeMap<>(m);
    s.entrySet().forEach(System.out::println);

Upvotes: 2

Related Questions