Java Array Cheatsheet
1. ARRAY BASICS & DECLARATION
Section titled “1. ARRAY BASICS & DECLARATION”// Declareint[] arr;int arr2[];String[] names;
// Initializeint[] arr = {1, 2, 3};int[] arr = new int[5]; // Default: 0String[] arr = new String[3]; // Default: null
// Lengtharr.length;
// Accessarr[0] = 10;int x = arr[2];Key Point: Arrays are fixed-size. Once created, size cannot change.
2. ARRAY CREATION & COPYING
Section titled “2. ARRAY CREATION & COPYING”Create New Arrays
Section titled “Create New Arrays”// Basic copy (shallow)int[] copy = arr.clone();int[] copy = Arrays.copyOf(arr, arr.length);
// Copy rangeint[] part = Arrays.copyOfRange(arr, 0, 3); // [0,3) - 3 exclusive
// Copy with SystemSystem.arraycopy(source, 0, dest, 0, length);Concatenate Arrays
Section titled “Concatenate Arrays”// Using System.arraycopyint[] result = new int[arr1.length + arr2.length];System.arraycopy(arr1, 0, result, 0, arr1.length);System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
// Using Streams (cleaner)int[] merged = IntStream.concat( Arrays.stream(arr1), Arrays.stream(arr2)).toArray();3. SEARCHING & CHECKING
Section titled “3. SEARCHING & CHECKING”// Contains elementArrays.asList(arr).contains(5);Arrays.stream(arr).anyMatch(x -> x == 5);
// Find indexint index = Arrays.asList(arr).indexOf(5); // -1 if not found
// Check sortedboolean sorted = IntStream.range(0, arr.length - 1) .noneMatch(i -> arr[i] > arr[i + 1]);
// Binary search (requires sorted array)int index = Arrays.binarySearch(arr, 5); // Returns index or (-(insertion point) - 1)4. SORTING
Section titled “4. SORTING”// Primitive array - ascendingArrays.sort(arr);
// Primitive array - descendingInteger[] arr = {3, 1, 4, 1, 5};Arrays.sort(arr, Collections.reverseOrder());
// Custom comparatorArrays.sort(arr, (a, b) -> b - a); // DescendingArrays.sort(arr, (a, b) -> a.compareTo(b)); // For objects
// Multiple fieldsArrays.sort(employees, Comparator .comparing(Employee::getFirstName) .thenComparing(Employee::getLastName));
// Streams (doesn't modify original)Integer[] sorted = Arrays.stream(arr) .sorted() .toArray(Integer[]::new);
Integer[] sorted = Arrays.stream(arr) .sorted(Collections.reverseOrder()) .toArray(Integer[]::new);5. AGGREGATION OPERATIONS
Section titled “5. AGGREGATION OPERATIONS”Sum & Average
Section titled “Sum & Average”// Sumint sum = Arrays.stream(arr).sum();long sum = 0;for(int x : arr) sum += x;
// Averagedouble avg = Arrays.stream(arr).average().orElse(0);
// Countlong count = Arrays.stream(arr).count();Min & Max
Section titled “Min & Max”// Minint min = Arrays.stream(arr).min().orElseThrow();int min = Collections.min(Arrays.asList(arr));
// Maxint max = Arrays.stream(arr).max().orElseThrow();int max = Collections.max(Arrays.asList(arr));
// Loop (efficient for arrays)int max = arr[0], min = arr[0];for(int x : arr) { max = Math.max(max, x); min = Math.min(min, x);}6. FILTERING & TRANSFORMATION
Section titled “6. FILTERING & TRANSFORMATION”// FilterInteger[] evens = Arrays.stream(arr) .filter(x -> x % 2 == 0) .toArray(Integer[]::new);
// Map/TransformInteger[] doubled = Arrays.stream(arr) .map(x -> x * 2) .toArray(Integer[]::new);
// Filter + MapString[] names = {"alex", "brian", "charles"};String[] caps = Arrays.stream(names) .filter(n -> n.length() > 4) .map(String::toUpperCase) .toArray(String[]::new);7. DUPLICATES & UNIQUE ELEMENTS
Section titled “7. DUPLICATES & UNIQUE ELEMENTS”Find Duplicates
Section titled “Find Duplicates”// Using MapMap<Integer, Long> map = Arrays.stream(arr) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() ));Integer[] dups = map.keySet().stream() .filter(k -> map.get(k) > 1) .toArray(Integer[]::new);
// Using SetSet<Integer> seen = new HashSet<>();Integer[] dups = Arrays.stream(arr) .filter(e -> !seen.add(e)) .toArray(Integer[]::new);Remove Duplicates
Section titled “Remove Duplicates”// Keep order with LinkedHashSetInteger[] unique = Arrays.stream(arr) .distinct() .toArray(Integer[]::new);
// Or use SetSet<Integer> uniqueSet = new LinkedHashSet<>(Arrays.asList(arr));Integer[] unique = uniqueSet.toArray(new Integer[0]);8. UNION & INTERSECTION
Section titled “8. UNION & INTERSECTION”Union (combine, remove duplicates)
Section titled “Union (combine, remove duplicates)”// HashSet approachHashSet<Integer> set = new HashSet<>();set.addAll(Arrays.asList(arr1));set.addAll(Arrays.asList(arr2));Integer[] union = set.toArray(new Integer[0]);
// Stream approachInteger[] union = Stream.of(arr1, arr2) .flatMap(Stream::of) .distinct() .toArray(Integer[]::new);Intersection (common elements)
Section titled “Intersection (common elements)”// HashSet approachHashSet<Integer> set = new HashSet<>(Arrays.asList(arr1));set.retainAll(Arrays.asList(arr2));Integer[] intersection = set.toArray(new Integer[0]);
// Stream approachInteger[] intersection = Arrays.stream(arr1) .distinct() .filter(x -> Arrays.asList(arr2).contains(x)) .toArray(Integer[]::new);9. SPLITTING ARRAYS
Section titled “9. SPLITTING ARRAYS”// Split at indexint[] part1 = Arrays.copyOfRange(arr, 0, 3);int[] part2 = Arrays.copyOfRange(arr, 3, arr.length);
// Split in halfint mid = arr.length / 2;int[] first = Arrays.copyOfRange(arr, 0, mid);int[] second = Arrays.copyOfRange(arr, mid, arr.length);
// Split into N parts (chunks)List<Integer[]> chunks = new ArrayList<>();int chunkSize = 3;for(int i = 0; i < arr.length; i += chunkSize) { int end = Math.min(i + chunkSize, arr.length); chunks.add(Arrays.copyOfRange(arr, i, end));}10. REMOVING ELEMENTS
Section titled “10. REMOVING ELEMENTS”// Remove by index (create new array)Integer[] result = new Integer[arr.length - 1];System.arraycopy(arr, 0, result, 0, index);System.arraycopy(arr, index + 1, result, index, arr.length - index - 1);
// Using List (easier)List<Integer> list = new ArrayList<>(Arrays.asList(arr));list.remove(Integer.valueOf(5)); // Remove valuelist.remove(2); // Remove by indexInteger[] result = list.toArray(new Integer[0]);
// Remove all occurrencesList<Integer> list = new ArrayList<>(Arrays.asList(arr));list.removeAll(Collections.singleton(5));Integer[] result = list.toArray(new Integer[0]);11. TOP N ELEMENTS
Section titled “11. TOP N ELEMENTS”// Using PriorityQueue (min-heap for top N)PriorityQueue<Integer> pq = new PriorityQueue<>();for(int x : arr) { pq.add(x); if(pq.size() > N) pq.poll();}// pq contains top N elements
// Using Streams (easier)Integer[] topN = Arrays.stream(arr) .sorted(Collections.reverseOrder()) .limit(N) .toArray(Integer[]::new);
// Reverse sortedInteger[] bottom N = Arrays.stream(arr) .sorted() .limit(N) .toArray(Integer[]::new);12. CONVERSIONS
Section titled “12. CONVERSIONS”Array ↔ List
Section titled “Array ↔ List”// Array to List (fixed-size, backed by array)List<Integer> list = Arrays.asList(arr);
// Array to List (independent, mutable)List<Integer> list = new ArrayList<>(Arrays.asList(arr));List<Integer> list = Arrays.stream(arr).collect(Collectors.toList());
// List to ArrayInteger[] arr = list.toArray(new Integer[0]);Integer[] arr = list.toArray(Integer[]::new);Primitive ↔ Object Array
Section titled “Primitive ↔ Object Array”// int[] to Integer[]Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new);
// Integer[] to int[]int[] unboxed = Arrays.stream(arr).mapToInt(Integer::intValue).toArray();String ↔ Array
Section titled “String ↔ Array”// String to String[]String[] words = "hello world java".split(" ");String[] words = Pattern.compile(" ").split("hello world java");
// String[] to StringString joined = String.join(" ", words);String joined = String.join(",", arr);String[] ↔ int[]
Section titled “String[] ↔ int[]”// String[] to int[]int[] nums = Arrays.stream(strArr) .mapToInt(Integer::parseInt) .toArray();
// Handle invalid valuesint[] nums = Arrays.stream(strArr).mapToInt(str -> { try { return Integer.parseInt(str); } catch(NumberFormatException e) { return -1; }}).toArray();
// String[] to Integer[]Integer[] nums = Arrays.stream(strArr) .map(Integer::parseInt) .toArray(Integer[]::new);13. PRINTING & DEBUGGING
Section titled “13. PRINTING & DEBUGGING”// Print arraySystem.out.println(Arrays.toString(arr));
// Print 2D arraySystem.out.println(Arrays.deepToString(arr2d));
// Print with custom formatArrays.stream(arr).forEach(x -> System.out.print(x + " "));Arrays.stream(arr).forEach(System.out::println);14. MULTI-DIMENSIONAL ARRAYS
Section titled “14. MULTI-DIMENSIONAL ARRAYS”// Declare 2Dint[][] matrix = new int[3][4];int[][] matrix = {{1,2}, {3,4}, {5,6}};
// Accessmatrix[0][1] = 5;
// Iteratefor(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { System.out.println(matrix[i][j]); }}
// Enhanced loopfor(int[] row : matrix) { for(int x : row) { System.out.println(x); }}
// Sum all elementsint sum = Arrays.stream(matrix) .flatMapToInt(Arrays::stream) .sum();15. COMMON DSA PATTERNS
Section titled “15. COMMON DSA PATTERNS”Prefix Sum
Section titled “Prefix Sum”int[] prefix = new int[arr.length];prefix[0] = arr[0];for(int i = 1; i < arr.length; i++) { prefix[i] = prefix[i-1] + arr[i];}Two Pointer
Section titled “Two Pointer”int left = 0, right = arr.length - 1;while(left < right) { // Do something if(condition) left++; else right--;}Sliding Window
Section titled “Sliding Window”int windowSum = 0;for(int i = 0; i < windowSize; i++) { windowSum += arr[i];}for(int i = windowSize; i < arr.length; i++) { windowSum = windowSum - arr[i - windowSize] + arr[i]; // Process windowSum}Frequency Array (for counting)
Section titled “Frequency Array (for counting)”int[] freq = new int[26]; // For 'a' to 'z'for(char c : str.toCharArray()) { freq[c - 'a']++;}QUICK REFERENCE TABLE
Section titled “QUICK REFERENCE TABLE”| Task | Method |
|---|---|
| Create copy | Arrays.copyOf(), clone() |
| Get subarray | Arrays.copyOfRange() |
| Search | Arrays.binarySearch(), contains() |
| Sort | Arrays.sort() |
| Sum/Avg | stream().sum(), average() |
| Min/Max | min(), max() |
| Filter | stream().filter() |
| Remove duplicates | distinct() |
| Convert to List | Arrays.asList() |
| Join string | String.join() |
| Split string | split() |
GOTCHAS TO AVOID
Section titled “GOTCHAS TO AVOID”- Arrays are fixed-size → Use ArrayList for dynamic sizing
- Shallow copy →
clone()copies references, not objects - Arrays.asList() is fixed-size → Changes reflect in original array
- Off-by-one errors →
copyOfRange(a, b, c)has c exclusive - Null for objects →
new String[5]contains null values - String.split() with regex → Escape special chars like
.,| - Primitive streams → Use
IntStream,LongStream,DoubleStream - Binary search → Array must be sorted first
- Performance → Loop > stream for simple operations on small arrays
- Memory → Creating new array for every operation is expensive
| Method | Purpose | Example |
|---|---|---|
Arrays.sort(array) | Sorts the array in ascending order (uses dual-pivot Quicksort for primitives). | java\nint[] arr = {5, 2, 8, 1};\nArrays.sort(arr);\nSystem.out.println(Arrays.toString(arr)); // [1, 2, 5, 8]\n |
Arrays.binarySearch(array, key) | Performs binary search on a sorted array. Returns index or negative if not found. | java\nint[] arr = {1, 2, 4, 6, 8};\nSystem.out.println(Arrays.binarySearch(arr, 4)); // 2\n |
Arrays.equals(arr1, arr2) | Checks if two arrays are equal in size and content. | java\nint[] a = {1, 2, 3};\nint[] b = {1, 2, 3};\nSystem.out.println(Arrays.equals(a, b)); // true\n |
Arrays.copyOf(array, newLength) | Copies the array into a new array with specified length. | java\nint[] arr = {1, 2, 3};\nint[] copy = Arrays.copyOf(arr, 5);\nSystem.out.println(Arrays.toString(copy)); // [1, 2, 3, 0, 0]\n |
Arrays.copyOfRange(array, from, to) | Copies a specific range from an array (from inclusive, to exclusive). | java\nint[] arr = {1, 2, 3, 4, 5};\nint[] part = Arrays.copyOfRange(arr, 1, 4);\nSystem.out.println(Arrays.toString(part)); // [2, 3, 4]\n |
Arrays.fill(array, value) | Fills the entire array with a given constant value. Useful for initialization. | java\nint[] arr = new int[5];\nArrays.fill(arr, -1);\nSystem.out.println(Arrays.toString(arr)); // [-1, -1, -1, -1, -1]\n |
Arrays.toString(array) | Converts array into a readable string for debugging. | java\nint[] arr = {1, 2, 3};\nSystem.out.println(Arrays.toString(arr)); // [1, 2, 3]\n |
Arrays.stream(array) | Creates a stream from an array (useful for quick operations like sum, min, max). | java\nint[] arr = {1, 2, 3};\nint sum = Arrays.stream(arr).sum();\nSystem.out.println(sum); // 6\n |
Arrays.asList(T... a) | Converts an array to a fixed-size List (works only for object arrays). | java\nString[] fruits = {\"Apple\", \"Banana\"};\nList<String> list = Arrays.asList(fruits);\nSystem.out.println(list); // [Apple, Banana]\n |