数组最常用方法

创造新数组

初始化

import org.apache.commons.lang3.ArrayUtils;
# 正常初始化
String[] arr = new String[] {"zyy", "zxx", "zww"};
String[] arr = {"wyy", "wzz", "wxx", "wxx"};

# ArrayUtils
String[] arr = ArrayUtils.toArray("a", "b", "c", "d", "e");

# Arrays
String[] arr = new String[4];
Arrays.fill(arr , "wyy");

# Java8对数组的支持
int[] ints = IntStream.rangeClosed(3, 9).toArray(); // [3, 4, 5, 6, 7, 8, 9]

复制数组

# Object
String[] strings5 = arr.clone();

# ArrayUtils
String[] strings6 = ArrayUtils.clone(arr);

截取子数组

# Arrays
String[] arr = {"wyy", "wzz", "wxx", "wxx", "asd"};
String[] strings1 = Arrays.copyOf(arr, 4);                      //[wyy, wzz, wxx, wxx]
String[] strings2 = Arrays.copyOfRange(arr, 0, 1);              //[wyy]
String[] strings3 = Arrays.copyOfRange(arr, 1, arr.length);     //[wzz, wxx, wxx, asd]
String[] strings4 = Arrays.copyOfRange(arr, 1, arr.length - 1); //[wzz, wxx, wxx]

# ArrayUtils
String[] strings5 = ArrayUtils.subarray(arr, 1, 3); // [wzz, wxx]

合并数组

int[] intArray = {1, 2, 88, 3, 4, 5};
int[] intArray2 = { 6, 7, 8, 9, 10 };

int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2); //create a new array
//[1, 2, 88, 3, 4, 5, 6, 7, 8, 9, 10]

每隔n个元素便返回

public static int[] everyNth(int[] elements, int nth) {
    return IntStream.range(0, elements.length).filter(i -> i % nth == nth - 1).map(i -> elements[i]).toArray();
}

null to []

String[] arr1 = null;
String[] strings = ArrayUtils.nullToEmpty(arr1);  // []

遍历

数组遍历

int[] s5 = new int[] {7, 3, 2, 8, 9};

for (Integer s : s5) {
    System.out.print(s + " ");
}

for (int i = 0; i < s5.length; i++) {
    System.out.print(s5[i] + " ");
}

下标

检查数组是否包含某个值

String[] stringArray = {"a", "b", "c", "d", "e"};
# Arrays
boolean b = Arrays.asList(stringArray).contains("a");
# ArrayUtils
boolean a = ArrayUtils.contains(stringArray, "a");

查找元素下标

# 查找元素第一次出现的下标
Integer[] array1 = {1, 1, 1, 2, 7, 11, 22, 37};
# Arrays
int i = Arrays.binarySearch(array1, 2); // 3
# ArrayUtils
int j = ArrayUtils.indexOf(array1, 2); // 3
int j = ArrayUtils.lastIndexOf(array1, 2); // 3

# 查找数组中元素的索引,在不存在元素的情况下返回-1
public static int indexOf(int[] elements, int el) {
    return IntStream.range(0, elements.length).filter(idx -> elements[idx] == el).findFirst().orElse(-1);
}
# 查找数组中元素的最后索引,在不存在元素的情况下返回-1
public static int lastIndexOf(int[] elements, int el) {
    return IntStream.iterate(elements.length - 1, i -> i - 1).limit(elements.length).filter(idx -> elements[idx] == el).findFirst().orElse(-1);
}

# 查找所有元素下标
String[] stringArray = {"a", "b", "c", "d", "a"};
BitSet a = ArrayUtils.indexesOf(stringArray, "a");   // {0, 4}
BitSet a = ArrayUtils.indexesOf(arr, "a", 2);        // 从下标为2开始查找3D这个值得所有下标

# 查找下标是否有效
ArrayUtils.isArrayIndexValid(null, 0)       // false
ArrayUtils.isArrayIndexValid([], 0)         // false
ArrayUtils.isArrayIndexValid(["a"], 0)      // true

查找并返回两个同类型数组之间第一个不匹配的索引

int[] array1 = {2, 7, 11, 22, 37};
int[] array2 = {2, 7, 11, 22, 37};
int[] array3 = {2, 7, 19, 31, 39, 56};

int index1 = Arrays.mismatch(array1, array2); //-1
int index2 = Arrays.mismatch(array1, array3); // 2

元素增删改查

插入元素

# Arrays

# ArrayUtils
# 从数组后添加元素
String[] stringArray = {"a", "b", "c", "d", "e"};
String[] fs = ArrayUtils.add(stringArray, "f"); // [a, b, c, d, e, f]

# 往数组里添加数组
String[] stringArray = {"a", "b", "c", "d", "e"};
String[] stringArray2 = {"a", "b", "c", "d", "e"};
String[] fs = ArrayUtils.addAll(stringArray, stringArray2); // [a, b, c, d, e, a, b, c, d, e]

# 从数组前添加元素
String[] stringArray = {"a", "b", "c", "d", "e"};
String[] fs = ArrayUtils.addFirst(stringArray, "t"); // [t, a, b, c, d, e]

# 插入元素到指定位置
 String[] stringArray = {"a", "a", "b", "c", "d", "a"};
 String[] zs = ArrayUtils.insert(1, stringArray, "z"); // [a, z, a, b, c, d, a]

移除数组中的元素

# Arrays

# ArrayUtils
# 删除指定位置元素 create a new array
ArrayUtils.remove(["a"], 0)           = []
ArrayUtils.remove(["a", "b"], 0)      = ["b"]
ArrayUtils.remove(["a", "b"], 1)      = ["a"]
ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"]

# 删除指定位置多个元素
ArrayUtils.removeAll([1], 0)             = []
ArrayUtils.removeAll([2, 6], 0)          = [6]
ArrayUtils.removeAll([2, 6], 0, 1)       = []
ArrayUtils.removeAll([2, 6, 3], 1, 2)    = [2]
ArrayUtils.removeAll([2, 6, 3], 0, 2)    = [6]
ArrayUtils.removeAll([2, 6, 3], 0, 1, 2) = []

# 删除所有指定元素
ArrayUtils.removeElement(null, true)                = null
ArrayUtils.removeElement([], true)                  = []
ArrayUtils.removeElement([true], false)             = [true]
ArrayUtils.removeElement([true, false], false)      = [true]
ArrayUtils.removeElement([true, false, true], true) = [false, true]

元素顺序

逆向一个数组

# Arrays

# ArrayUtils
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);  // [5, 4, 3, 2, 1]

移动数组的顺序

# Arrays

# ArrayUtils
# Shifts the order of the given int array
String[] stringArray1 = {"a", "b", "c", "d", "e"};
ArrayUtils.shift(stringArray1,1); // [e, a, b, c, d]

String[] stringArray = {"a", "b", "c", "d", "e"};
ArrayUtils.shift(stringArray,2); // [d, e, a, b, c]

String[] stringArray2 = {"a", "b", "c", "d", "e"};
ArrayUtils.shift(stringArray2,3); // [c, d, e, a, b]

String[] stringArray3 = {"a", "b", "c", "d", "e"};
ArrayUtils.shift(stringArray3,4); // [b, c, d, e, a]

String[] stringArray4 = {"a", "b", "c", "d", "e"};
ArrayUtils.shift(stringArray4,5); //  [a, b, c, d, e]

String[] stringArray5 = {"a", "b", "c", "d", "e"};
ArrayUtils.shift(stringArray5,6);// 6%5 ->1 取模 [e, a, b, c, d]

交换数组两元素位置

# Arrays

# ArrayUtils
ArrayUtils.swap(["1", "2", "3"], 0, 2) -> ["3", "2", "1"]
ArrayUtils.swap(["1", "2", "3"], 0, 0) -> ["1", "2", "3"]
ArrayUtils.swap(["1", "2", "3"], 1, 0) -> ["2", "1", "3"]
ArrayUtils.swap(["1", "2", "3"], 0, 5) -> ["1", "2", "3"]
ArrayUtils.swap(["1", "2", "3"], -1, 1) -> ["2", "1", "3"]

编辑元素

编辑每个元素

# Arrays
double[] a = {1.0, 2.0, 3.0, 4.4};
Arrays.setAll(a, x -> a[x] * a[x]);
[1.0, 4.0, 9.0, 19.360000000000003]

# ArrayUtils

Java8流式用法

Double[] stringArray = {1D, 2D, 3D, 11D, 22D, 33D, 111D, 222D, 333D};
Arrays.stream(stringArray).filter(a -> a > 2D).forEach(aDouble -> System.out.print(aDouble + " 、")); 
// 3.0 、11.0 、22.0 、33.0 、111.0 、222.0 、333.0 、

相等

数据equals

Integer[] array1 = {1, 1, 1, 2, 7, 11, 22, 37};
Integer[] array2 = {1, 1, 1, 2, 7, 11, 22, 37};
# Arrays
boolean equals = Arrays.equals(array1, array2); // true
boolean equals = Arrays.equals(array1, 2, 4, array2, 2, 4); // true
boolean equals = Arrays.equals(array1, array2, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return (o1 < o2  ? -1 : (o1.equals(o2) ? 0 : 1));
    }
});  // true
boolean equals4 = Arrays.equals(array1, array2, (o1, o2) -> (o1 < o2 ? -1 : (o1.equals(o2) ? 0 : 1)));

数据结构间切换

数组 to string

String[] s1 = {"wyy", "wzz", "wxx", "wxx"};

# String
String str4 = String.join(",", s1); // wyy,wzz,wxx,wxx

# StringUtils
String str3 = StringUtils.join(s1, ","); // wyy,wzz,wxx,wxx

# Arrays
String str1 = Arrays.toString(s1); // [wyy, wzz, wxx, wxx]

# ArrayUtils
String str2 = ArrayUtils.toString(s1); // {wyy,wzz,wxx,wxx}

# java8
String str5 = Arrays.stream(s1).collect(Collectors.joining(",")); // wyy,wzz,wxx,wxx

数组 to List

String[] s2 = {"wyy", "wzz", "wxx", "wxx"};
# Arrays
List<String> list = Arrays.asList(s2);

# java9
List<String> list = List.of(s2);

# List
List<String> list = new ArrayList<>(Arrays.asList(s2));
List<String> list = new ArrayList<>(List.of(s2));

List to 数组

Integer[] list = integers2.toArray(Integer[]::new);
Integer[] list = integers2.toArray(new Integer[0]);
Integer[] list = integers2.toArray(new Integer[integers2.size()]);

字符串,数组,集合之间相互转换总结

数组 to Set

# set
Set<String> set = new HashSet<>(Arrays.asList(s2));

数组 to Map

Map colorMap = ArrayUtils.toMap(new String[][] {
    {"RED", "#FF0000"},
    {"GREEN", "#00FF00"},
    {"BLUE", "#0000FF"}
});

输出

打印二维数组

//  打印二维数组
int[][] ints = new int[][]{{1, 2, 3}, {4, 5, 6}};

Arrays.stream(ints).forEach(a -> System.out.println(Arrays.toString(a)));

[1, 2, 3]
[4, 5, 6]

字节数组

将整数转换为字节数组

byte[] bytes = ByteBuffer
    .allocate(i)        // 从堆空间中分配缓冲区4个字节
    .putInt(1000)       // 向ByteBuffer写数据
    .array();

# 传统
for (byte t : bytes) {
    System.out.format("0x%x ", t);
}

# java8
// Stream.of(bytes).forEach(a -> System.out.format("0x%x ", a)); 报错
IntStream.range(0, bytes.length).forEach(i -> System.out.format("0x%x ", bytes[i]));

4字节表示: 0x0 0x0 0x3 0xe8 
5字节表示: 0x0 0x0 0x3 0xe8 0x0 
6字节表示: 0x0 0x0 0x3 0xe8 0x0 0x0 
7字节表示: 0x0 0x0 0x3 0xe8 0x0 0x0 0x0 
8字节表示: 0x0 0x0 0x3 0xe8 0x0 0x0 0x0 0x0 
9字节表示: 0x0 0x0 0x3 0xe8 0x0 0x0 0x0 0x0 0x0 

以字节为单位返回字符串的长度

public static int byteSize(String input) {
    return input.getBytes().length;
}

基本方法

boolean a = ArrayUtils.isEmpty(arr1);
boolean b = ArrayUtils.isNotEmpty(arr1);
boolean b = ArrayUtils.isSameType(arr1,arr2);     // 判断两个数组的类型是否相同
boolean b = ArrayUtils.isSameLength(arr1,arr2);   // 判断两个数组的长度是否相同,要同类型;
boolean b = ArrayUtils.isSorted(arr1);            // 判断数组是否以自然顺序排序

参考

stackoverflow中票数最多的数组操作方法
斩草除根学ArrayUtils
斩草除根学Arrays

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值