Apache工具类Pair和Triple详解

 org.apache.commons.lang3 工具包依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Apache Commons Lang3 是一个 Java 工具库,提供了许多实用的类和方法,可以帮助开发人员更加便捷地编写 Java 程序。该库提供了一些常见的工具类,包括:

ArrayUtils:提供了一系列静态方法来操作数组,例如数组的复制、查找、比较等操作。

StringUtils:提供了一系列静态方法来操作字符串,例如字符串的比较、替换、分割等操作。

ObjectUtils:提供了一些静态方法来操作对象,例如对象的比较、空值检查等操作。

BooleanUtils:提供了一些静态方法来操作布尔类型的数据,例如布尔值的转换、判断等操作。

NumberUtils:提供了一些静态方法来操作数字类型的数据,例如数字的转换、判断等操作。

        除此之外,还提供了一些有用的数据结构封装,比如返回多个值的数据结构Pair(2个值)和Triple(3个值)

1、Pair 的详细解析     
        Apache Commons Lang3是一个常用的Java工具库,其中的Pair类可以用于存储一对值,类似于一个二元组。Pair类是一个泛型类,可以存储任意两种类型的值。

        以下是Pair类的构造方法和方法列表:
 

public Pair(L left, R right) // 构造函数,创建一个具有给定左值和右值的Pair对象
 
public L getLeft() // 返回左值
 
public R getRight() // 返回右值
 
public void setLeft(L left) // 设置左值
 
public void setRight(R right) // 设置右值
 
public void setValue(L left, R right) // 同时设置左值和右值
 
public boolean equals(Object obj) // 判断两个Pair对象是否相等
 
public int hashCode() // 返回Pair对象的哈希码
 
public String toString() // 返回Pair对象的字符串表示

       可以看到,Pair类提供了许多方法来操作其包含的两个值。除了构造函数和获取/设置方法之外,Pair还提供了equals和hashCode方法,这使得它可以用作Map的键或集合的元素。toString方法返回一个格式为"(left,right)"的字符串,用于调试和日志记录。

        下面是一个简单的示例,说明如何使用Pair类:
 

import org.apache.commons.lang3.tuple.Pair;
 
public class PairExample {
    public static void main(String[] args) {
        Pair<String, Integer> pair = Pair.of("John", 25);
        System.out.println("Name: " + pair.getLeft()); // 输出"Name: John"
        System.out.println("Age: " + pair.getRight()); // 输出"Age: 25"
        pair.setValue("Bob", 30);
        System.out.println("Name: " + pair.getLeft()); // 输出"Name: Bob"
        System.out.println("Age: " + pair.getRight()); // 输出"Age: 30"
    }
}

 

在这个示例中,我们创建了一个Pair对象,其中左值是一个字符串"John",右值是一个整数25。然后我们使用getLeft和getRight方法获取左值和右值,并使用setValue方法更改它们。最后,我们再次使用getLeft和getRight方法来检查更改是否已生效。

ImmutablePair和MutablePair

   ImmutablePair和MutablePair是Apache Commons Lang库中的两个类,用于表示具有两个值的键值对。// Pair 类的实现类

   ImmutablePair是一个不可变的类,一旦创建,就不能更改其值,表示一个只读的键值对。它的构造函数接受两个参数,分别是键和值,并且它还提供了一些方法来获取键和值的值。例如,可以使用getLeft()方法获取键的值,使用getRight()方法获取值的值。

   MutablePair是一个可变的类,可以在创建之后更改其值,表示一个可变的键值对。其他与ImmutablePair类似。

        这两个类都实现了Map.Entry接口,因此可以将它们作为键值对添加到Map中。此外,它们还实现了Serializable接口,因此可以将它们序列化为字节数组并在网络上传输或保存到文件中。

public static void main(String[] args) {
        Pair<Integer, Integer> pair = Pair.of(1, 10); //同ImmutablePair.of(1, 10)
        System.out.println(pair.getLeft()); //1
        System.out.println(pair.getRight()); //10
        //pair.setValue(30); //报错:java.lang.UnsupportedOperationException
 
        pair = MutablePair.of(1, 10);
        ((MutablePair<Integer, Integer>) pair).setLeft(100);
        ((MutablePair<Integer, Integer>) pair).setRight(200);
        System.out.println(pair.getLeft()); //100
        System.out.println(pair.getRight()); //200
        pair.setValue(200); //备注setValue同setRight方法
    }

应用场景:Pair类是一个灵活的工具类,适用于许多需要存储一对值的场景。它可以简化代码并提高代码的可读性和可维护性。 

2、Triple 的详细解析
        Apache Commons Lang3库中的Triple类是一个泛型类,可以存储三个值。类似于Pair类,Triple类也可以用于将多个值封装在一起,以便于传递、比较或存储。

        以下是Triple类的构造方法和方法列表:
 

public Triple(L left, M middle, R right) // 构造函数,创建一个具有给定左值、中值和右值的Triple对象
 
public L getLeft() // 返回左值
 
public M getMiddle() // 返回中值
 
public R getRight() // 返回右值
 
public void setLeft(L left) // 设置左值
 
public void setMiddle(M middle) // 设置中值
 
public void setRight(R right) // 设置右值
 
public void setValue(L left, M middle, R right) // 同时设置左值、中值和右值
 
public boolean equals(Object obj) // 判断两个Triple对象是否相等
 
public int hashCode() // 返回Triple对象的哈希码
 
public String toString() // 返回Triple对象的字符串表示

        与Pair类类似,Triple类也提供了许多方法来操作其包含的三个值。除了构造函数和获取/设置方法之外,Triple还提供了equals和hashCode方法,这使得它可以用作Map的键或集合的元素。toString方法返回一个格式为"(left,middle,right)"的字符串,用于调试和日志记录。

        下面是一个简单的示例,说明如何使用Triple类:
 

import org.apache.commons.lang3.tuple.Triple;
 
public class TripleExample {
    public static void main(String[] args) {
        Triple<String, Integer, Boolean> triple = Triple.of("John", 25, true);
        System.out.println("Name: " + triple.getLeft()); // 输出"Name: John"
        System.out.println("Age: " + triple.getMiddle()); // 输出"Age: 25"
        System.out.println("IsMale: " + triple.getRight()); // 输出"IsMale: true"
        triple.setValue("Bob", 30, false);
        System.out.println("Name: " + triple.getLeft()); // 输出"Name: Bob"
        System.out.println("Age: " + triple.getMiddle()); // 输出"Age: 30"
        System.out.println("IsMale: " + triple.getRight()); // 输出"IsMale: false"
    }
}

        在这个示例中,我们创建了一个Triple对象,其中左值是一个字符串"John",中值是一个整数25,右值是一个布尔值true。然后我们使用getLeft、getMiddle和getRight方法获取三个值,并使用setValue方法更改它们。最后,我们再次使用getLeft、getMiddle和getRight方法来检查更改是否已生效。

        Triple类是一个灵活的工具类,适用于许多需要存储三个值的场景。

3、实用案例:使用Pair封装指定时间的时间间隔

        使用Pair获取指定时间的时间间隔代码如下:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
 
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
 
 
/**
 * 日期帮助类
 *
 * @Date 2022/7/11 15:17
 */
public class DateUtil {
 
    /**
     * 获取(1-本周 2-本月 3-本季度)
     *
     * @return {@link Pair< LocalDate, LocalDate>}
     * @date 2022/7/11 15:36
     */
    public static Pair<LocalDate, LocalDate> getByDateType(Integer dateType,LocalDate localDate) {
        LocalDate today = LocalDate.now();
        if (localDate!=null){
            today = localDate;
        }
        if (dateType == null ){
            return  null;
        }
        if (dateType == 1) { // 本周
            return ImmutablePair.of(today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)), // 星期一
                today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))); // 星期天
        }
        if (dateType == 2) { // 本月
            return ImmutablePair.of(today.with(TemporalAdjusters.firstDayOfMonth()), //月的第一天
                today.with(TemporalAdjusters.lastDayOfMonth())); // 月的最后一天
        }
        if (dateType == 3) { // 本季度
            Month month = today.getMonth();
            Month firstMonthOfQuarter = month.firstMonthOfQuarter();
            Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
            return ImmutablePair.of(LocalDate.of(today.getYear(), firstMonthOfQuarter, 1),
                LocalDate.of(today.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(today.isLeapYear())));
        }
        return null;
    }
}

 

    /**
     * 获取指定日的时间间隔
     */
    public static Pair<LocalDateTime, LocalDateTime> getDayIntervalTime(LocalDateTime localDateTime) {
        LocalDateTime dateTime = getDateTime(localDateTime);
        return ImmutablePair.of(LocalDateTime.of(dateTime.toLocalDate(), LocalTime.MIN),
            LocalDateTime.of(dateTime.toLocalDate(), LocalTime.MAX));
    }
 
    /**
     * 获取指定日,本周的时间间隔
     */
    public static Pair<LocalDateTime, LocalDateTime> getWeekIntervalTime(LocalDateTime localDateTime) {
        LocalDateTime dateTime = getDateTime(localDateTime);
        return ImmutablePair
            .of(dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).withHour(0).withMinute(0).withSecond(0),
                dateTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).withHour(23).withMinute(59).withSecond(59));
    }
 
    /**
     * 获取指定日,本月的时间间隔
     */
    public static Pair<LocalDateTime, LocalDateTime> getMonthIntervalTime(LocalDateTime localDateTime) {
        LocalDateTime dateTime = getDateTime(localDateTime);
        return ImmutablePair.of(dateTime.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0),
            dateTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59));
    }
 
    /**
     * 获取指定日,本季的时间间隔
     */
    public static Pair<LocalDateTime, LocalDateTime> getQuarterIntervalTime(LocalDateTime localDateTime) {
        LocalDateTime dateTime = getDateTime(localDateTime);
        Month month = dateTime.getMonth();
        Month firstMonthOfQuarter = month.firstMonthOfQuarter();
        Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
        return ImmutablePair.of(LocalDateTime.of(dateTime.getYear(), firstMonthOfQuarter, 1, 0, 0, 0),
            LocalDateTime.of(dateTime.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(dateTime.toLocalDate().isLeapYear()), 23,
                59, 59));
    }
 
    /**
     * 获取指定日,年的时间间隔
     */
    public static Pair<LocalDateTime, LocalDateTime> getYearIntervalTime(LocalDateTime localDateTime) {
        LocalDateTime dateTime = getDateTime(localDateTime);
        return ImmutablePair.of(dateTime.with(TemporalAdjusters.firstDayOfYear()).withHour(0).withMinute(0).withSecond(0),
            dateTime.with(TemporalAdjusters.lastDayOfYear()).withHour(23).withMinute(59).withSecond(59));
    }
 
    public static LocalDateTime getDateTime(LocalDateTime localDateTime) {
        LocalDateTime dateTime = localDateTime;
        return Objects.isNull(dateTime) ? LocalDateTime.now() : localDateTime;
    } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值