本文共 2971 字,大约阅读时间需要 9 分钟。
集合排序:已知在一个ArrayList中有若干个Person对象,将这些Person对象按照年龄降序排序。
public class Exercise1 { public static void main(String[] args) { ArrayListlist = new ArrayList<>(); list.add(new Person("aaa", 10)); list.add(new Person("bbb", 11)); list.add(new Person("ccc", 12)); list.add(new Person("ddd", 13)); list.add(new Person("eee", 14)); list.add(new Person("fff", 15)); list.sort((o1, o2) -> o2.age - o1.age); System.out.println(list); }}
TreeSet排序
public class Exercise2 { public static void main(String[] args) { /* TreeSet */ TreeSetset = new TreeSet<>((o1, o2) -> { if(o1.age >= o2.age){ return -1; }else{ return 1; } }); set.add(new Person("aaa", 10)); set.add(new Person("bbb", 11)); set.add(new Person("ccc", 12)); set.add(new Person("ddd", 13)); set.add(new Person("eee", 14)); set.add(new Person("fff", 15)); System.out.println(set); }}
集合遍历(带条件)
public class Exercise3 { public static void main(String[] args) { /* 集合遍历 */ ArrayListlist = new ArrayList<>(); Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0); //将集合中的每一个元素都带入到方法accept中。 list.forEach(System.out::println); //输出集合中所有的偶数 list.forEach(ele -> { if(ele % 2 == 0) System.out.println(ele); }); }}
条件删除
public class Exercise4 { public static void main(String[] args) { //删除集合中满足条件的元素 ArrayListlist = new ArrayList<>(); list.add(new Person("aaa", 10)); list.add(new Person("bbb", 11)); list.add(new Person("ccc", 12)); list.add(new Person("ddd", 13)); list.add(new Person("eee", 14)); list.add(new Person("fff", 15)); //删除集合中年龄大于12岁的元素/* ListIterator it = list.listIterator(); while(it.hasNext()){ Person ele = it.next(); if(ele.age > 12){ it.remove(); } }*/ //Lambda实现,将集合中的每一个元素都带入到test方法中,如果返回值是true,则删除这个元素 list.removeIf(ele -> ele.age > 12); System.out.println(list); }}
开启线程
public class Exercise5 { public static void main(String[] args) { //需求:开辟一条线程,做一个数字的输出 Thread t = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 100; i++){ System.out.println(i); } } }); t.start(); Thread t2 = new Thread(() -> { for(int i = 0; i < 100; i++){ System.out.println(i); } }); t2.start(); }}
转载地址:http://zupqb.baihongyu.com/