JDK1.8对Map的最新排序方法

1.传统排序:

//对值进行排序,此处为降序
public static > Map sortByValueDescending(Map map)
    {
        List> list = new LinkedList>(map.entrySet());
        Collections.sort(list, new Comparator>()
        {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2)
            {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return -compare;
            }
        });

        Map result = new LinkedHashMap();
        for (Map.Entry entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

2.新排序方法:

public static > Map sortByValue(Map map, boolean asc) 
    {
        Map result = new LinkedHashMap<>();
        Stream> stream = map.entrySet().stream();    
		if (asc) //升序
		{
			 //stream.sorted(Comparator.comparing(e -> e.getValue()))
			stream.sorted(Map.Entry.comparingByValue())
				.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
		else //降序
		{
			 //stream.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
			stream.sorted(Map.Entry.comparingByValue().reversed())
				.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
        return result;
    }

public static , V > Map sortByKey(Map map, boolean asc) 
	{
        Map result = new LinkedHashMap<>();
        Stream> stream = map.entrySet().stream();
        if (asc) 
		{
        	stream.sorted(Map.Entry.comparingByKey())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        else 
		{
        	stream.sorted(Map.Entry.comparingByKey().reversed())
            	.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
	    return result;
	}

3.上面的知识点补充:

jdk1.8新特性:

    a. 新增Lambda表达式和函数式接口;

    b. 新增Stream API(java.util.stream);

其他新特性见文章:https://blog.csdn.net/u014470581/article/details/54944384

 

                ---------------------------------------------欢迎关注公众号(生活不止有代码)-------------------------------------------------------

                                                                      JDK1.8对Map的最新排序方法_第1张图片

你可能感兴趣的:(工具,Java)