Java8 常用集合操作

Java8 常用集合操作

List操作

List<Student> list = new ArrayList<>();  
// 遍歷
list.forEach(item ->{
      System.out.println("\n"+item.getAge()+":"+item.getSex());
});

// 過濾
list.stream().filter(item-> item.getAge() > 18).collect(Collectors.toList());

// 排序,bean裏面實現compareTo接口
list.stream().sorted((s1,s2) -> s1.getAge().compareTo(s2.getAge())).collect(Collectors.toList());
// 不實現compareTo接口,必須要用一個集合接收,不然沒有效果
List<Student> resultStudent = new ArrayList<>();  
resultStudent.addAll(list.stream().sorted((v1, v2) -> {
				// 這裏是倒序
                return v1.getAge() - v2.getAge() > 0 ? -1 : 1;
            }).collect(Collectors.toList()));


//將集合按照默認的規則排序,按照數字從小到大的順序排序
Collections.sort(list);
//將集合中的元素反轉
Collections.reverse(list);
//打亂集合中的元素
Collections.shuffle(list);


Map操作

Map<String, Long> allYearList = new ConcurrentHashMap<>();
 // 按鍵倒序
Map<String, Long> resultYear = allYearList.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByKey().reversed()).collect(
        Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldVal, newVal) -> oldVal, LinkedHashMap::new)
);

 // 按值倒序
Map<String, Long> resultYear = allYearList.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).collect(
        Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldVal, newVal) -> oldVal, LinkedHashMap::new)
);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章