Square values in array list

In mathematics, a square number or perfect square is an integer that is the square of an integer. In other words it is a number multiplied by a number and can be written as 4 x 4. In the snippets below we will show how to square an arraylist of numbers using plain java, java 8 and guava.

Straight up Java

@Test
public void square_vals_in_array() {
    
    List<Integer> numbers = new ArrayList<Integer>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    
    for(Integer num : numbers) {
        System.out.println(num * num);
    }
    
    // or
    List<Integer> result = new ArrayList<Integer>();
    for (Integer digit : numbers) {
        result.add(digit * digit);
    }
    
    assertThat(result, containsInAnyOrder(
            1, 4, 9));
}

Java 8

First loading an array list with a series of random numbers we will show two different ways approaches that result in the same output. Creating a function that will result in a number multiple by itself, we will convert the an arraylist to a stream and call the map function passing in the function square. Next using the java 8 forEach we will iterate and output the numbers. The second snippet will perform the same operations but collect the values back to a list.

@Test
public void square_list_values_8() {

    List<Integer> numbers = new ArrayList<Integer>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);

    Function<Integer, Integer> square = x -> x * x;
    numbers.stream().map(square).forEach(x -> System.out.println(x));

    // or
    List<Integer> squareNumbers = numbers.stream().map(square)
            .collect(Collectors.toList());
    
    assertThat(squareNumbers, containsInAnyOrder(
            1, 4, 9));
}

Google Guava

@Test
public void square_list_values_guava() {

    com.google.common.base.Function<Integer, Integer> squaredFunction = 
            new com.google.common.base.Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer input) {
            return input * input;
        }
    };

    List<Integer> units = new ArrayList<Integer>();
    units.add(1);
    units.add(2);
    units.add(3);

    List<Integer> squareUnits = Lists.transform(units, squaredFunction);

    assertThat(squareUnits, containsInAnyOrder(1, 4, 9));
}

ReactiveX - RXJava

This snippet will show how to square values in a sequence using RxJava. First, we will creating a function using java 8 syntax that accepts one value and then multiplies it by itself. Next, using the Observable.from method will convert the List to an Observable so it will emit the items to the sequence. Calling the map method we will apply the square function to each of the values.

@Test
public void square_list_values_rxjava() {

    Func1<Integer, Integer> square = (x) -> x * x;

    Observable.from(Arrays.asList(1, 2, 3, 4, 5))
        .map(square)
        .subscribe(System.out::println);
}

Output

1
4
9
16
25