使用lambda運算式操作HashMap,lambdahashmap

來源:互聯網
上載者:User

使用lambda運算式操作HashMap,lambdahashmap

Java8之前,如果想根據map的value值來排序話,比較繁瑣參看《如何將HashMap,按照value值排序 》

現在藉助於lambda運算式,就方便多了。

Map<String,Integer> map=new HashMap<>();map.put("derek",24 );map.put("dad", 51);map.put("mom", 46);List<Map.Entry<String, Integer>> list=new ArrayList<>();list.addAll(map.entrySet());//Collections.sort(list,new Comparator<Map.Entry<String, Integer>>(){//public int compare(Map.Entry<String, Integer> m1,Map.Entry<String, Integer> m2){//return m1.getValue()-m2.getValue();//}//});Collections.sort(list,(m1, m2) ->m1.getValue()-m2.getValue());list.forEach(m -> System.out.println(m.getKey()));

注釋掉的部分就是之前的方式,現在只需要簡短的一行代碼就可以搞定,遍曆也方便了不少。

lambda運算式給Java帶來的函數式編程果然犀利,再加上Java8中強化的類型推斷,代碼變得簡潔易懂~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.