1. 说明
某些业务需要特定的元素在列表的最后或者指定位置展示。
2. 代码
import lombok.AllArgsConstructor;
import lombok.Data;import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;@Data
@AllArgsConstructor
class Student {String name;int age;
}public class TList {public static void main(String[] args) {List<Student> list = getList();System.out.println("原始list:" + list);// 按照年龄排序list = list.stream().sorted(Comparator.comparing(a -> a.getAge(),Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());System.out.println("按照年龄排序list:" + list);// 将18的排在最后面// 获取18的下标List<Student> finalList = list;OptionalInt first = IntStream.range(0, list.size()).filter(i -> finalList.get(i).getAge() == 18).findFirst();if (first.isPresent()) {// 通过下标移除list中的原数据Student remove = list.remove(first.getAsInt());// 再次放入listlist.add(remove);}System.out.println("18年龄排序list:" + list);// list add 还有个重载方法,可以指定下标放入Student s6 = new Student("剑圣", 52);list.add(2, s6);System.out.println("插入后list:" + list);// 扩展,Collections.swap 可以交换list中的元素Collections.swap(list, 1, 3);System.out.println("交换后list:" + list);}/*** 生成初始列表** @return {@link List}<{@link Student}>*/static List<Student> getList() {List<Student> list = new ArrayList<>();Student s1 = new Student("小炮", 81);Student s2 = new Student("人马", 35);Student s3 = new Student("精灵", 10);Student s4 = new Student("娜迦", 18);list.add(s1);list.add(s2);list.add(s3);list.add(s4);return list;}
}
(图网,侵删)