Concatenate arrays and ignore null array @param arrays arrays to merge @param array component type @return the concatenated array
(T[]... arrays)
| 36 | * @return the concatenated array |
| 37 | */ |
| 38 | @SuppressWarnings("unchecked") |
| 39 | public static <T> T[] concat(T[]... arrays) { |
| 40 | if (null == arrays || 0 == arrays.length) return null; |
| 41 | |
| 42 | int resultLength = |
| 43 | java.util.Arrays.stream(arrays) |
| 44 | .filter(Objects::nonNull) |
| 45 | .map(e -> e.length) |
| 46 | .reduce(0, Integer::sum); |
| 47 | T[] resultArray = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), resultLength); |
| 48 | |
| 49 | for (int i = 0, n = arrays.length, curr = 0; i < n; i++) { |
| 50 | T[] array = arrays[i]; |
| 51 | |
| 52 | if (null == array) continue; |
| 53 | |
| 54 | int length = array.length; |
| 55 | System.arraycopy(array, 0, resultArray, curr, length); |
| 56 | curr += length; |
| 57 | } |
| 58 | |
| 59 | return resultArray; |
| 60 | } |
| 61 | |
| 62 | private Arrays() {} |
| 63 | } |