List接口新增默认方法sort
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
Person p1 = new Person("东子",12);
Person p2 = new Person("东子",10);
Person p3 = new Person("东子",19);
Person p4 = new Person("东子",22);
List<Person> list = Arrays.asList(p1,p2,p3,p4);
//根据年龄排序
list.sort((v1 ,v2) -> v1.getAge() - v2.getAge());
//字符串 根据自动顺序排序
list.sort((v1 ,v2) -> v1.getName().compareTo(v2.getName()) );
Iterable 接口新增默认方法foreach
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
Person p1 = new Person("东子",12);
Person p2 = new Person("东子",10);
Person p3 = new Person("东子",19);
Person p4 = new Person("东子",22);
List<Person> list = Arrays.asList(p1,p2,p3,p4);
list.forEach(value -> System.out.println(value.getAge()));
传统方式:
Java8 方式:
list.stream().distinct().collect(Collectors.toList());
需求:字符串 a-b-c , a-f-c-d , a-b-d-e 用"-"分割 后去重
传统方式:
①:分割字符串-》string[]
②:string[] -> List
③:多个list 通过hash 、等方法 去重
Java8:利用流中 flatMap
flatMap :将流【数组流 Stream】
里面的多个T容器进行合并 , 返回合并后的Stream[T] 流
// 案例 -- 数组合并去重
List<String> list = Arrays.asList("a-b-c","a-b-c-e","a-b-d-e");
List<String> collect = list.stream()
//将流中元素切割处理 返回Stream<String[]>
.map(item -> item.split("-"))
//flatMap 方法 将多个String[] 变为 一个list
.flatMap(item -> Stream.of(item))
.distinct().collect(Collectors.toList());
//打印
collect.forEach(System.out::println);
================================================================
// 案例2 -- 集合合并去重
List<String> l1 = Arrays.asList("a","b","c");
List<String> l2 = Arrays.asList("b","a","d");
List<String> l3 = Arrays.asList("a","c","d");
List<String> l4 = Arrays.asList("b","c","e");
List<String> l5 = Arrays.asList("a","c","d");
List<List<String>> list = Arrays.asList(l1,l2,l3,l4,l5);
List<String> collect = list.stream().
flatMap(item -> item.stream())
.distinct() //去重
.collect(Collectors.toList());//终止操作 转为对应的list
//打印
collect.forEach(System.out::println);