Using Apache Commons Math with collections

Ahoy matey! Are you ready to learn about how to use collections of objects with Apache Commons Math? Collections be like a treasure trove of valuable items, and with Apache Commons Math, you can easily store and manipulate those treasures.
Creating collections of objects
Collections are a way of storing multiple objects in one place, and there are many different types of collections to choose from. In Apache Commons Math, we have access to a variety of collection classes, including ArrayList, LinkedList, and ArrayRealVector.
Let’s start with ArrayList, which is a basic implementation of a resizable array. To create an ArrayList, we simply import the class and then create a new instance:
import org.apache.commons.math3.util.ArrayList;
ArrayList<String> myArrayList = new ArrayList<String>();
In this example, we’re creating an ArrayList of strings, but we can create ArrayLists of any type of object. Once we have our ArrayList, we can add objects to it using the add() method:
myArrayList.add("gold coins");
myArrayList.add("treasure map");
myArrayList.add("cutlass");
We can also retrieve objects from our ArrayList using the get() method:
String firstItem = myArrayList.get(0);
In this example, we’re retrieving the first item in our ArrayList and storing it in a string variable called firstItem.
Another useful collection class in Apache Commons Math is LinkedList, which is similar to ArrayList but provides faster insertion and deletion of items at the cost of slower random access. To create a LinkedList, we follow a similar process as creating an ArrayList:
import org.apache.commons.math3.util.LinkedList;
LinkedList<String> myLinkedList = new LinkedList<String>();
We can then add items to our LinkedList using the add() method:
myLinkedList.add("spyglass");
myLinkedList.add("parrot");
And retrieve items using the get() method:
String secondItem = myLinkedList.get(1);
In this example, we’re retrieving the second item in our LinkedList and storing it in a string variable called secondItem.
Finally, there’s ArrayRealVector, which is a specialized collection class for storing numeric data. To create an ArrayRealVector, we first import the class and then create a new instance:
import org.apache.commons.math3.linear.ArrayRealVector;
ArrayRealVector myVector = new ArrayRealVector();
We can then add numeric data to our vector using the setEntry() method:
myVector.setEntry(0, 3.14159);
myVector.setEntry(1, 2.71828);
In this example, we’re setting the first and second entries in our vector to the values of pi and e, respectively.
And that’s it for creating collections of objects with Apache Commons Math! But hold fast, there’s still more to learn. Stay tuned for our next installment, where we’ll cover sorting and filtering collections, as well as using common collection classes.
Sorting and filtering collections
Now that we know how to create collections of objects in Apache Commons Math, let’s take a look at how we can sort and filter those collections to make them even more useful.
Sorting collections
Sorting is the process of arranging the items in a collection in a specific order, such as alphabetical or numerical. In Apache Commons Math, we can use the sort() method to sort our collections.
Let’s say we have an ArrayList of integers:
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(5);
myNumbers.add(3);
myNumbers.add(7);
We can sort this ArrayList in ascending order using the sort() method:
Collections.sort(myNumbers);
After this code runs, our ArrayList will be sorted to [3, 5, 7].
We can also sort in descending order by using a custom comparator. For example, let’s say we have an ArrayList of strings:
ArrayList<String> myWords = new ArrayList<String>();
myWords.add("parrot");
myWords.add("cutlass");
myWords.add("spyglass");
We can sort this ArrayList in descending order of length by creating a custom comparator and passing it to the sort() method:
Comparator<String> descendingLengthComparator = new Comparator<String>() {
public int compare(String s1, String s2) {
return Integer.compare(s2.length(), s1.length());
}
};
Collections.sort(myWords, descendingLengthComparator);
After this code runs, our ArrayList will be sorted to [“spyglass”, “cutlass”, “parrot”].
Filtering collections
Filtering is the process of selecting a subset of items from a collection based on a specific criterion. In Apache Commons Math, we can use the filter() method to filter our collections.
Let’s say we have an ArrayList of integers:
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(5);
myNumbers.add(3);
myNumbers.add(7);
We can filter this ArrayList to only include even numbers using the filter() method:
myNumbers = (ArrayList<Integer>) CollectionUtils.select(myNumbers, new Predicate<Integer>() {
public boolean evaluate(Integer n) {
return n % 2 == 0;
}
});
After this code runs, our ArrayList will only contain the number 5.
We can also filter collections based on more complex criteria by creating custom predicates. For example, let’s say we have an ArrayList of strings:
ArrayList<String> myWords = new ArrayList<String>();
myWords.add("parrot");
myWords.add("cutlass");
myWords.add("spyglass");
We can filter this ArrayList to only include words that contain the letter “a” using a custom predicate:
Predicate<String> containsAPredicate = new Predicate<String>() {
public boolean evaluate(String s) {
return s.contains("a");
}
};
myWords = (ArrayList<String>) CollectionUtils.select(myWords, containsAPredicate);
After this code runs, our ArrayList will only contain the words “parrot” and “cutlass”.
And that’s it for sorting and filtering collections with Apache Commons Math! In the next installment, we’ll cover using common collection classes, so keep a weather eye on the horizon.
Using common collection classes
In addition to the basic collection classes we covered earlier, Apache Commons Math provides several common collection classes that are useful for various mathematical operations.
Array2DRowRealMatrix
Array2DRowRealMatrix is a class for representing matrices in Apache Commons Math. We can create an Array2DRowRealMatrix by passing a two-dimensional array of doubles to the constructor:
double[][] data = { {1.0, 2.0}, {3.0, 4.0} };
Array2DRowRealMatrix myMatrix = new Array2DRowRealMatrix(data);
We can then perform basic matrix operations on our matrix, such as addition, multiplication, and transposition:
double[][] newData = { {5.0, 6.0}, {7.0, 8.0} };
Array2DRowRealMatrix otherMatrix = new Array2DRowRealMatrix(newData);
Array2DRowRealMatrix sumMatrix = myMatrix.add(otherMatrix);
Array2DRowRealMatrix productMatrix = myMatrix.multiply(otherMatrix);
Array2DRowRealMatrix transposeMatrix = myMatrix.transpose();
OpenMapRealVector
OpenMapRealVector is a class for representing sparse vectors in Apache Commons Math. We can create an OpenMapRealVector by specifying the size of the vector and the non-zero entries:
int size = 3;
double[] values = {1.0, 0.0, 2.0};
OpenMapRealVector myVector = new OpenMapRealVector(size, values);
We can then perform basic vector operations on our vector, such as addition, dot product, and normalization:
double[] newValues = {0.0, 1.0, 3.0};
OpenMapRealVector otherVector = new OpenMapRealVector(size, newValues);
OpenMapRealVector sumVector = myVector.add(otherVector);
double dotProduct = myVector.dotProduct(otherVector);
OpenMapRealVector normalizedVector = myVector.unitVector();
RealDistribution
RealDistribution is a class for representing probability distributions in Apache Commons Math. We can create a RealDistribution by specifying the type of distribution and its parameters:
RealDistribution normalDistribution = new NormalDistribution(0.0, 1.0);
RealDistribution exponentialDistribution = new ExponentialDistribution(1.0);
We can then use our distribution to generate random numbers or calculate probabilities:
double randomSample = normalDistribution.sample();
double probability = normalDistribution.cumulativeProbability(0.0);
And that’s it for our brief overview of common collection classes in Apache Commons Math! By using these classes in combination with the basic collection classes we covered earlier, you can perform a wide variety of mathematical operations in Java. We hope you found this article helpful, and happy programming!