Lambda表達式對List的簡單操作


------------恢復內容開始------------

1:常見List排序,可以使用 Collections 工具類操作  sort() 、reverse() 等等

List<Integer> intList = new ArrayList<Integer>();
intList.add(12);
intList.add(33);
intList.add(15);
intList.add(22);
intList.add(45);
intList.forEach(System.out::println);
System.out.println("====================");
Collections.sort(intList);
intList.forEach(System.out :: println);
Collections.reverse(intList);
System.out.println("====================");
intList.forEach(System.out :: println);
System.out.println("====================");
intList.forEach((item) -> item.);

2:使用lambda 表達式 通過添加filter對數據做篩選

  1>測試類

@Data
class Demo {
Integer id;
String name;
Integer age;
Demo(){}
Demo(Integer a,String b, Integer c){id=a; name = b; age = c;}
}
2>簡單應用
 public static void main(String args[]) {
ArrayList<Demo> intArr = new ArrayList<Demo>();
intArr.add(new Demo(1,"Lee", 18));
intArr.add(new Demo(2,"stone", 30));
intArr.add(new Demo(6,"john", 18));
intArr.forEach(System.out::println);
System.out.println("================================");
intArr.forEach(item -> System.out.println(item.age));
System.out.println("================================");
//設置過濾器
Predicate<Demo> filter = p -> p.getId() > 2;
      //自定義構造方法姓名按字母升序排序
// List<Demo> sortArr = intArr.stream().sorted((a, b ) -> (a.getName().compareTo(b.getName()))).collect(Collectors.toList());
      //通過過濾器篩選集合數據
List<Demo> sortArr = intArr.stream().filter(filter).sorted((a, b ) -> (a.getId() - b.getId())).collect(Collectors.toList());
sortArr.forEach((item) -> System.out.println(item));

}

 

  

------------恢復內容結束------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM