一、元組的概念
元組是指將多個數據項組合成一個不可變的序列。Java不支持元組,但可以使用第三方庫如javatuples或google-guava提供的元組實現。
//使用javatuples庫創建元組
Unit<String> unit = Unit.with("Hello");
Pair<String,Integer> pair = Pair.with("Hello", 1);
Triplet<String,Integer,Double> triplet = Triplet.with("Hello", 1, 1.2);
//使用google-guava庫創建元組
ImmutablePair<String,Integer> pair = ImmutablePair.of("Hello", 1);
ImmutableTriple<String,Integer,Double> triplet = ImmutableTriple.of("Hello", 1, 1.2);
元組可以用於返回多個值,作為函數參數傳遞多個參數,或者存儲多個數據,方便管理。
二、元組的作為返回值
對於一個函數需要返回多個值的情況,可以使用元組作為函數的返回值。
public static Triplet<Integer,Integer,Integer> getMinMaxSum(int[] arr){
int min = arr[0];
int max = arr[0];
int sum = 0;
for(int i=0;i<arr.length;i++){
sum += arr[i];
if(arr[i] < min){
min = arr[i];
}
if(arr[i] > max){
max = arr[i];
}
}
return Triplet.with(min,max,sum);
}
//調用getMinMaxSum函數
int[] arr = {1,2,3,4,5};
Triplet<Integer,Integer,Integer> result = getMinMaxSum(arr);
System.out.println("最小值:"+result.getValue0()+";最大值:"+result.getValue1()
+";元素和:"+result.getValue2());
getMinMaxSum函數接受一個整數數組,返回該數組的最小值、最大值及所有元素的和,使用Triplet作為函數的返回值。
三、元組作為函數的參數
使用元組作為函數的參數,可以簡化函數的定義,減少參數數量。
public static int arraySum(Triplet<int[],Integer,Integer> tuple){
int[] arr = tuple.getValue0();
int start = tuple.getValue1();
int end = tuple.getValue2();
int sum = 0;
for(int i=start;i<=end;i++){
sum += arr[i];
}
return sum;
}
//調用arraySum函數
int[] arr = {1,2,3,4,5};
Triplet<int[], Integer, Integer> tuple = Triplet.with(arr, 1, 3);
int sum = arraySum(tuple);
System.out.println("數組部分元素和:"+sum);
arraySum函數接受一個Triplet類型的參數,包含一個整數數組和要求和的數組下標起止位置,返回部分元素的和。
四、元組的數據存儲
我們經常使用map集合存儲鍵值對,但是有時候需要存儲多個值,元組可以為我們提供存儲多個值的解決方案。
Map<String,Pair<Integer,Integer>> map = new HashMap<>();
map.put("Jack", ImmutablePair.of(18,180));
map.put("Tom", ImmutablePair.of(20,175));
System.out.println("Jack的年齡:"+map.get("Jack").getValue0()+
";Jack的身高:"+map.get("Jack").getValue1());
我們使用map存儲了多組鍵值對,鍵是一個字元串,值是一個二元組,包含一個整數代表年齡和一個整數代表身高。
五、多種元組的比較
不同元組的實現使用的是不同的模板參數,因此它們之間不具有可比性。Java提供了Comparable介面來實現元組之間的比較。
public class AgeComparator implements Comparator<Unit<String>>{
@Override
public int compare(Unit<String> o1, Unit<String> o2) {
int age1 = Integer.parseInt(o1.getValue0());
int age2 = Integer.parseInt(o2.getValue0());
return age1-age2;
}
}
//使用AgeComparator比較兩個Unit類型的元組。
Unit<String> unit1 = Unit.with("18");
Unit<String> unit2 = Unit.with("20");
List<Unit<String>> list = new ArrayList<>();
list.add(unit1);
list.add(unit2);
Collections.sort(list, new AgeComparator());
System.out.println(list.get(0).getValue0());
通過實現比較器介面,我們可以比較不同類型的元組,上述代碼中比較兩個Unit類型的元組,輸出第一個元組的值。
原創文章,作者:LOKV,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/138059.html
微信掃一掃
支付寶掃一掃