lambda HashMap 排序

TreeMap

  • 按key排序生成map可以有TreeMap 完成,TreeMap可以按key的自然顺序排序(Comparable实现)

lambda comparingByKey

使用lambda也可以很方便的对map排序

  • Map.Entry.comparingByKey() 按key排序的Comparator
  • Map.Entry.comparingByValue()按value排序的Comparator
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class MapSortDemo {
    public static void main(String[] args) {
        User user1 = new User("zs", 10);
        User user2 = new User("ls", 5);
        User user3 = new User("wu", 20);
        Map map = new HashMap<>();
        map.put(user1.getName(), user1);
        map.put(user2.getName(), user2);
        map.put(user3.getName(), user3);

        System.out.println("------map sort by key------");
        map.entrySet().
                stream().
                sorted(Map.Entry.comparingByKey()).
                forEach(System.out::println);

        System.out.println("------map sort by value------");
        map.entrySet().
                stream().
                sorted(Map.Entry.comparingByValue()).
                forEach(System.out::println);


        System.out.println("------return sorted by key map ------");
        TreeMap treeMap=new TreeMap<>(map);
        System.out.println(treeMap);

        System.out.println("------return sorted by value map ------");
        Map result = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        System.out.println(result);
    }

}

class User implements Comparable {
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(User o) {
        return this.getAge() - o.getAge();
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

output

------map sort by key------
ls=User{name='ls', age=5}
wu=User{name='wu', age=20}
zs=User{name='zs', age=10}
------map sort by value------
ls=User{name='ls', age=5}
zs=User{name='zs', age=10}
wu=User{name='wu', age=20}
------return sorted by key map ------
{ls=User{name='ls', age=5}, wu=User{name='wu', age=20}, zs=User{name='zs', age=10}}
------return sorted by value map ------
{ls=User{name='ls', age=5}, zs=User{name='zs', age=10}, wu=User{name='wu', age=20}}

你可能感兴趣的:(lambda HashMap 排序)