排序
// 数组Integer[] nums = { 3, 1, 4, 5, 8, 3, 2 };// 使用Arrays.sort方法,默认大小顺序排序,打印:[1, 2, 3, 3, 4, 5, 8]Arrays.sort(nums);// 使用Collections.reverseOrder方法,按照大小逆序排序,打印:[8, 5, 4, 3, 3, 2, 1]Arrays.sort(nums, Collections.reverseOrder());// 自定义顺序(用lambda表达式表示函数时间接口Comparator,实现compare方法),打印:[8, 5, 4, 3, 3, 2, 1]Arrays.sort(nums, (x, y) -> y - x);String[] strs = { "a", "bc", "zef", "knc", "bac", "jklh" };// 使用Arrays.sort方法,按照字母顺序排序,打印:[a, bac, bc, jklh, knc, zef]Arrays.sort(strs);// 使用Collections.reverseOrder方法,按照字母逆序排序,打印:[zef, knc, jklh, bc, bac, a]Arrays.sort(strs, Collections.reverseOrder()); // 自定义顺序(用lambda表达式表示函数式接口Comparator,实现compare方法),打印:[jklh, bac, knc, zef, bc, a]Arrays.sort(strs, (x, y) -> y.length() - x.length());Dog[] dogs = new Dog[2];dogs[0] = new Dog("James", 150.0, "Kan", 1);dogs[1] = new Dog("kans", 140.0, "crash", 1);// 根据狗主人名字的长度,进行倒序排序(数组对象示例)Arrays.sort(dogs, (x, y) -> y.getMasterName().length() - x.getMasterName().length());// SmallDog实现了Comparable类,实现方法默认为根据值顺序SmallDog[] dogs = { new SmallDog(1), new SmallDog(3), new SmallDog(2) };// 打印:[SmallDog[age=1], SmallDog[age=3], SmallDog[age=2]]System.out.println(Arrays.toString(dogs));// 打印:[SmallDog[age=1], SmallDog[age=2], SmallDog[age=3]]Arrays.sort(dogs);// 打印:[SmallDog[age=3], SmallDog[age=2], SmallDog[age=1]]Arrays.sort(dogs, (x, y) -> Integer.compare(y.getAge(), x.getAge()));// 数组对象列表List<SmallDog> dogs1 = new ArrayList<>();dogs1.add(dogs[0]);dogs1.add(dogs[1]);dogs1.add(dogs[2]);// 直接使用Collections.sort方法(前提是SmallDog类实现了Comparable接口)// 打印:[SmallDog[age=1], SmallDog[age=2], SmallDog[age=3]]Collections.sort(dogs1);// 打印:[SmallDog[age=3], SmallDog[age=2], SmallDog[age=1]]Collections.sort(dogs1, (x, y) -> Integer.compare(y.getAge(), x.getAge()));
过滤
/** * 根据SmallDog对象中的age值进行过滤 */// 数组List<SmallDog> filters1 = new ArrayList<>();for (SmallDog item : dogs) { if (item.getAge() == 2) { filters1.add(item); }}// 打印:[SmallDog[age=2]]System.out.println(filters1);// 数组列表List<SmallDog> filters2 = dogs1.stream() .filter(x -> x.getAge() == 1) .collect(Collectors.toList());// 打印:[SmallDog[age=1]]System.out.println(filters2);
批量处理
for (SmallDog item : dogs) { item.setName("DD" + item.getAge());}// 打印:SmallDog[name=DD1,age=1]]System.out.println(Arrays.toString(dogs));dogs1.stream().forEach(item -> { item.setName("DD" + item.getAge());});// 打印:[SmallDog[name=DD3,age=3], SmallDog[DD2,age=2], SmallDog[name=DD1,age=1]]System.out.println(dogs1);
聚合返回数据
String[] namesStr = new String[dogs.length()];List<String> names = new ArrayList<>();for (int i = 0; i < dogs.length(); i++) { namesStr[i] = dogs[i].getName(); names.add(dogs[i].getName());}List<String> names1 = dogs1.stream() .map(item -> item.getName()) .collect(Collectors.toList());