JavaSE之日期集合操作


日期、正则表达式、单列集合

1、日期

JDK8之前

// 获取时间戳
System.out.println(System.currentTimeMillis());

      Runtime r = Runtime.getRuntime();
      // 获取虚拟机可以处理的处理器数量
      System.out.println(r.availableProcessors());

      // 获取Java虚拟机中的内存总量  单位:字节
      System.out.println(r.totalMemory() / 1024 / 1024 + " MB");

      // 获取Java虚拟机中的可用内存量 单位:字节
      System.out.println(r.freeMemory() / 1024 / 1024 + " MB");

      // 启动某个程序,并返回该程序的对象
      Process p = r.exec("D:\\AppByMyselfDownload\\Lives\\QQ\\QQ.exe");
      Thread.sleep(10000);  // 暂停10s后 销毁
      p.destroy(); // 停止已运行的对象

日期类的使用-Date

Date date = new Date();
   System.out.println(date);  // 当前时间 Wed Nov 13 20:53:16 CST 2024

   date.getTime();  // 拿到当前时间的毫秒值(时间戳)
   long T = System.currentTimeMillis();

   // 把时间毫秒值(时间戳)转化成日期对象
   T += 2 * 1000;  // 2S后的时间戳
   Date date1 = new Date(T);
   System.out.println(date1);

格式化解析时间类-SimpleDateFormat

/*格式化时间*/
// 1.获取当前时间
Date now = new Date();
System.out.println(now);

// 2.创建日期格式化对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE a");

// 格式化时间戳
String format = sdf.format(now.getTime());
System.out.println(format);
// 格式化当前时间
String format1 = sdf.format(now);
System.out.println(format1);

/*把字符串时间 解析为日期对象*/
String strTime = "2024-1-13 21:22:14";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse = sdf2.parse(strTime);
System.out.println(parse);

日历类-calender 可变对象,一旦修改成功,对象本身表示的时间将会发生变化

// 1.得到此刻系统时间的日历对象
Calendar now = Calendar.getInstance();
System.out.println(now);

// 2.获取日历中的信息
int year = now.get(Calendar.YEAR);
System.out.println(year);

// 3.拿到日历中记录的日期对象
Date date = now.getTime();
System.out.println(date);

// 4.拿到时间毫秒值
long timeInMillis = now.getTimeInMillis();
System.out.println(timeInMillis);

// 5.修改日历中的信息
int value = 9;  // 10月
now.set(Calendar.MONTH, value);

// 6.为某个信息增加或减少指定值
now.add(Calendar.MONTH,-1);
System.out.println(now);

JDK8新增

image-20241113215522615

        LocalDate ld = LocalDate.now();
        System.out.println(ld);

        LocalTime lt = LocalTime.now();
        System.out.println(lt);

        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);

        // 显然LocalDateTime更为强大,所以比较常用
//        1. 获取信息
        int year = ldt.getYear();
        System.out.println(year);
        Month month = ldt.getMonth();
        System.out.println(month);
        int monthValue = ldt.getMonthValue();
        System.out.println(monthValue);
        int day = ldt.getDayOfMonth();
        System.out.println(day);

//        2. 修改信息
        LocalDateTime withYear = ldt.withYear(2025);
        System.out.println(withYear);

//        3. 加多少
        LocalDateTime plussedYears = ldt.plusYears(2);
        System.out.println(plussedYears);

//        4. 减多少
        LocalDateTime minusedYears = ldt.minusYears(2);
        System.out.println(minusedYears);

//        5. 获取指定的日期时间对象
        LocalDateTime time = LocalDateTime.of(2025, 1, 1, 1, 1,1,1);
        System.out.println(time);

//        6. 比较两个日期
        boolean equals = ldt.equals(plussedYears);
        System.out.println(equals);
        boolean before = ldt.isBefore(plussedYears);
        System.out.println(before);

image-20241114134723688

        Instant now = Instant.now();
        System.out.println(now);

//        不到1秒的纳秒数
        int nano = now.getNano();
        System.out.println(nano);

//        获取总秒数
        long epochSecond = now.getEpochSecond();
        System.out.println(epochSecond);

image-20241114135057897

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();

        /*正向格式化*/
        String format = formatter.format(now);
        System.out.println(format);

        /*逆向格式化*/
        System.out.println(now.format(formatter));

        /*解析字符串时间*/
        String time = "2024-12-14 14:03:52";
// PS:
        LocalDateTime parse = LocalDateTime.parse(time, formatter);
        System.out.println(parse);

2、Lambda表达式

image-20241114143151797

image-20241114144010214

3、正则表达式

image-20241114150141464

4、集合操作

image-20241114150648713

5、单列集合

image-20241114150839209

6、Collection集合

image-20241114152947345

ArrayList集合

Collection<String> c = new ArrayList<>();
//1.public boolean add(E e):添加元素,添加成功返回true
c.add("java");
c.add("C++");
c.add("python");
System.out.println(c);   //[java, C++, python]
//2.public void clear():清空集合的元素
c.clear();
System.out.println(c);  //[]
//3.public boolean isEmpty():判断集合是否为空 是空返回true,反之
boolean isEmpty = c.isEmpty();
System.out.println(isEmpty);
//4.public int size():获取集合的大小
int size = c.size();
System.out.println(size);
//5.public boolean contains(object obj):判断集合中是否包含某个元素
boolean havaJava = c.contains("java");
System.out.println(havaJava);
// 6.public boolean remove(E e):删除某个元素:如果有多个重复元素默认删除前面的第一个
boolean delPython = c.remove("python");
System.out.println(delPython);
System.out.println(c);
// 7.public Object[] toArray():把集合转换成数组
Object[] array = c.toArray();
String string = Arrays.toString(array);
System.out.println(string);

集合遍历—>迭代器-增强for-Lambda表达式

image-20241114154046564

	    Collection<String> name = new ArrayList<>();
        name.add("李星云");
        name.add("张子凡");
        name.add("姬如雪");
        name.add("陆林轩");

        Iterator<String> iterator = name.iterator();
// 迭代器遍历        
        while (iterator.hasNext()){
            String it = iterator.next();
            System.out.println(it);
        }
	  
// 增强for遍历集合或数组
	  for (String s : name) {
            System.out.println(s);
        }
// Lambda表达式
	       name.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        });
//---> 简化1
    name.forEach(
                s -> System.out.println(s)
        );
//---> 简化2
	name.forEach(
                System.out::println
        );

List接口

image-20241114163152774

image-20241114163254529

//1.创建一个ArrayList集合对象(有序、可重复、有索引)
        List<String> name = new ArrayList<>();
        name.add("李星云");
        name.add("张子凡");
        name.add("姬如雪");
        name.add("陆林轩");
        System.out.println(name);
//2.public void add(int index,E element):在某个索引位置插入元素。
        name.add(2,"袁天罡");
        System.out.println(name);
//3.publicE remove(int index):根据索引删除元素,返回被删除元素
        String remove = name.remove(4);
        System.out.println(remove);
        System.out.println(name);
//4.public E get(int index): 返回集合中指定位置的元素。
        String s = name.get(3);
        System.out.println(s);
// 5.public E set(int index,E element): 修改索引位置处的元素,修改成功后,会返回原来的数据
        String set = name.set(2, "陆林轩");
        System.out.println(set);
        System.out.println(name);

ArrayList原理

image-20241114164158954

image-20241114164300715

LinkedList原理

image-20241114164444167

image-20241114164542153

image-20241114164625414

image-20241114164718775

Set接口

image-20241114165051652

哈希值

image-20241114165359102

HashSet底层原理

image-20241114165624767

image-20241114165848716

如果需要去重,需要重写hashCode() 和 equals() 方法。

LinkedHashSet底层原理

image-20241114170200466

image-20241114172609700

TreeSet底层原理

image-20241114180028939

image-20241114180240406

package com.dapixiu;

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Set<Student> students = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return Double.compare(o1.getHeight(), o2.getHeight());
            }
        });
// 简化 Set<Student> students = new TreeSet<>(( o1,  o2) -> Double.compare(o1.getHeight(), o2.getHeight()) );
        students.add(new Student("a", 18, 165.6));
        students.add(new Student("b", 19, 165.7));
        students.add(new Student("c", 20, 165.8));

        Object[] array = students.toArray();
        System.out.println(Arrays.toString(array));
    }
}

class Student {
    private String name;
    private int age;
    private double height;

    Set<String> names = new HashSet<>();

    public Student() {
    }

    public Student(String name, int age, double height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", height=" + height +
                ", names=" + names +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }
}

单列集合总结

image-20241114182451438

集合的并发修改异常问题-ConcurrentModificationException

List<String> list = new ArrayList<>();

list.add("王麻子");
list.add("小李子");
list.add("李爱华");
list.add("李玉刚");

Iterator<String> it = list.iterator(); 
while (it.hasNext()) {
    String name = it.next();
    if (name.contains("李")) {
        list.remove(name);
    }
}
// 迭代器方案修正,删除迭代器当前遍历到的数据,每删除一个数据后,相当于在底层也做了 i--
Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String name = it.next();
            if (name.contains("李")) {
                it.remove();
            }
        }

// 或者倒叙处理
        for (int i = list.size() - 1; i >= 0; i--) {
            if (list.get(i).contains("李")) list.remove(i);
        }
        System.out.println(list);

image-20241114185442295

可变参数

image-20241114190140429

  • 可变参数在方法内部,其本质上还是一个数组。
  • 一个形参列表中,只可以有一个可变参数

Collections—>操作集合的工具类

image-20241114190413385

        List<String> names = new ArrayList<>();

//1、public static <T> boolean addAll(Collection<? super T>c,T...elements):为集合批量添加数据
        Collections.addAll(names, "李星云", "张子凡", "姬如雪", "陆林轩");
        System.out.println(names);

//2、public static void shuffle(List<?>list):打乱List集合中的元素顺序。
        Collections.shuffle(names);
        System.out.println(names);

//3、public static <T>void sort(List<T>list):对 List 集合中的元素进行升序排序
        ArrayList<Integer> nums = new ArrayList<>();
        Collections.addAll(nums, 1, 2, 3, 6, 2, 3, 1, 3);
        Collections.sort(nums);
        System.out.println(nums);

//4、public static <T> void sort(List<T> list,Comparator<?superT>c):对List集合中元素,按照比较器对象指定的规则进行排序
        Collections.sort(nums, (o1, o2) -> o2 - o1);
        System.out.println(nums);

7、双列集合

Map集合

image-20241114192712342

image-20241114193126087

  Map<String, Integer> map = new HashMap<>();
//        1.无需 不重复 无索引
        map.put("Vivo", 3999);
        map.put("Iqoo", 1999);
        map.put("Oppo", 5999);
        map.put("Realme", 2699);
        System.out.println(map);

//        2.获取集合的大小
        int size = map.size();
        System.out.println(size);

//        3.清空集合
        map.clear();

//        4.判断是否为空
        boolean empty = map.isEmpty();

//5.public V get(object key):根据键获取对应值
        Integer vioo = map.get("Vivo");
        System.out.println(vioo);

//6.publicV remove(object key):根据键删除整个元素(删除键会返回键的值):
        Integer vivo = map.remove("Vivo");

//7.public boolean containsKey(0bject key):判断是否包含某个键 ,包含返回true,反之
        boolean b = map.containsKey("Vivo");

//8.public boolean containsValue(object value): 判断是否包含某个值。
        boolean b1 = map.containsValue(1999);

//9.public Set<K> keySet():获取Map集合的全部键。
        Set<String> ks = map.keySet();

//10.public Collection<V> values();获取Map集合的全部值。
        Collection<Integer> values = map.values();
        System.out.println(values);

Map遍历

image-20241114200219135

键找值

image-20241114195632562

        Map<String, Integer> map = new HashMap<>();
//        1.无序 不重复 无索引
        map.put("Vivo", 3999);
        map.put("Iqoo", 1999);
        map.put("Oppo", 5999);
        map.put("Realme", 2699);
        System.out.println(map);

// 获取全部键值
        Set<String> ks = map.keySet();
// 根据键查找值
        for (String k : ks) {
            Integer y = map.get(k);
            System.out.println(k + ":" + y);
        }

键值对

image-20241114200550517

Map<String, Integer> map = new HashMap<>();
map.put("Vivo", 3999);
map.put("Iqoo", 1999);
map.put("Oppo", 5999);
map.put("Realme", 2699);
System.out.println(map);

Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " : " + value);
}

Lambda表达式

image-20241114201055548

Map<String, Integer> map = new HashMap<>();
map.put("Vivo", 3999);
map.put("Iqoo", 1999);
map.put("Oppo", 5999);
map.put("Realme", 2699);

map.forEach((k, v) -> System.out.println(k + " : " + v));

HashMap底层原理

image-20241114202953186

image-20241114205840157

LinkedHashMap底层原理

image-20241114210716811

TreeMap底层原理

image-20241114210934300

集合嵌套

Map<String, List<String>> map = new HashMap<>();

List<String> cities = new ArrayList<>();

map.put("江苏省", cities);
Collections.addAll(cities, "苏州", "南京", "马鞍山");

System.out.println(map);

文章作者: ZhangYao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ZhangYao !
  目录