Java notes

miscellaneous java notes

// initialize an array of ints
int[] arr = {2, 3, 10, 2, 4, 8, 1};
System.out.println(Arrays.toString(arr));

// initialize an array of Integers
Integer[] irr = {2, 3, 10, 2, 4, 8, 1};
System.out.println(Arrays.toString(irr));

// convert int[] to List<Integer>
List<Integer> aList = new ArrayList<>(arr.length);
for (int i : arr) aList.add(i);
System.out.println(Arrays.toString(aList.toArray()));

// this won't work because int is a primitive type
// List<int[]> bList = Arrays.asList(arr);
// System.out.println(Arrays.toString(bList.toArray())); // this won't work

// but this will because Integer is a reference type
List<Integer> cList = Arrays.asList(irr); // Arrays.asList(2, 3, 10, 2, 4, 8, 1);
System.out.println(Arrays.toString(cList.toArray()));

// in java 8, we can use Arrays.stream
System.out.println(Arrays.toString(Arrays.stream(arr).boxed().toArray()));

// IntStream outputs the same as Arrays.stream
System.out.println(Arrays.toString(IntStream.of(arr).boxed().toArray()));

// we don't need to use boxed() if we pass in Integer[]
System.out.println(Arrays.toString(Arrays.stream(irr).toArray()));

remember, generic types must be reference types so this won’t work:

List<int> list = new ArrayList<int>(); // this doesn't work

instead use reference types:

List<Integer> list = new ArrayList<Integer>();

reverse an int array in java

in-place method:

for(int i = 0; i < validData.length / 2; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

using streams in Java 8:

int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
                      .toArray(); //Output: [5, 4, 3, 2, 1]

reverse sort (descending) int[] array

static int[] reverseArray(int[] arr) {
    int[] ints = Arrays.stream(arr).boxed()
            .sorted(Collections.reverseOrder())
            .mapToInt(Integer::intValue)
            .toArray();
    return ints;
}

static List<Integer> reverseList(int[] arr) {
    List<Integer> integers = Arrays.stream(arr).boxed()
            .sorted(Collections.reverseOrder())
            .collect(Collectors.toList());
    return integers;
}

convert string array to int array in Java 8

String[] s = {"1", "2", "3", "4", "5"};

int[] arr1 = Arrays.stream(s).mapToInt(Integer::parseInt).toArray();
int[] arr2 = Stream.of(s).mapToInt(Integer::parseInt).toArray();

get sum of int array

int sum = IntStream.of(a).sum();
int sum = IntStream.of(a).parallel().sum();
IntStream.range(0, a).forEach(i -> st1.add(i, sc.nextInt()))

© 2020 | Paul Kim