下面算法使用的Student类
class Student implements Comparable<Student>{ private final String name; private final Integer age; public Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } @Override public int compareTo(Student o) { // 先按照name排序,如果名字相同,在按照age排序 if(this.name.compareTo(o.name) == 0){ return this.age-o.age; } return this.name.compareTo(o.name); } }
-
1, 排序
//排序 List<Student> students = new ArrayList<Student>(); for(int i = 0; i < 10; i++){ students.add(new Student("a"+i%4, i%3)); students.add(new Student("b"+i%4, i%3)); } Collections.sort(students); // 对Students进行排序 for(Student s:students){ System.out.println(s.getName()+":"+s.getAge()); }
-
2,二分查找
// 如果二分查找传入的容器不是随机访问的,效率就会退化为线性查找 List<Student> students = new ArrayList<Student>(); for(int i = 0; i < 10; i++){ students.add(new Student("a"+i%4, i%3)); students.add(new Student("b"+i%4, i%3)); } for(Student s:students){ System.out.println(s.getName()+":"+s.getAge()); } Collections.sort(students); Student p = new Student("a2",2); // 二分查找,如果返回值为正,表示所在容器的索引,如果返回负值,则表示插入位置在-i-1; int i = Collections.binarySearch(students,p); System.out.println(i);
-
3,交集
var l1 = List.of(1,2,3,2,5,7); var l2 = List.of(1,4,5,10,2,3,7); var s1 = new HashSet<Integer>(l1); //var s2 = new HashSet<Integer>(l2); s1.retainAll(l2); // 保留s1中存在于s2中的元素 s1.forEach((i)->{ System.out.println(i); });
-
4,list转array,array转list
String[] names = {"zhangsan", "lisi", "wangwu"}; List<String> nameList = List.of(names); //数组转list String[] values = nameList.toArray(String[]::new); //集合转数组要给一个数组构造器表达式 //jdk11之前 String[] v = nameList.toArray(new String[0]); //或者数组很长的情况下,重用原数组,不会创建新的数组 //String[] v = nameList.toArray(new String[mameList.size()]);
-
5,BitSet简单使用(实现素数筛法)
// 素数筛法 int n = 2000000; long start = System.currentTimeMillis(); var bitSet = new BitSet(n+1); // 定义一个2000001的位集 int i; for(i = 2; i <= n; i++){ bitSet.set(i); // 将所有位打开 } i = 2; while (i*i <= n){ if(bitSet.get(i)){ // 如果当前位是打开的,则进行处理 int k = i*i; while (k <= n){ // 将i的倍数的位全部关闭 bitSet.clear(k); k += i; } } i ++; } long end = System.currentTimeMillis(); System.out.println(bitSet.cardinality()+"素数"); // 返回打开的位(set) System.out.println((end-start)+"milliseconds");