Java Review: Regular Expressions, Comparators, and Collections.

Regular expressions-

Regular expressions are statements that provide a search term syntax for strings. The String class has several functions that utilize regular expressions including

.matches(),

.replaceAll(),

.split().

Regular expressions use special syntax to denote allowed or disallowed characters in a string. These are excellent for input sanitization as you can tell it what to look for. Some of the most useful regEx syntax to know is that a period, ‘.’, denotes a single character; so ’J..a’ would match any four letter word beginning with J and ending with a.

The asterisk ,‘*’, character denotes 0 + characters in an unknown fashion. This is useful when you’re searching for starting characters. You can have a regular expression that searches for words beginning with w that would read ‘w.*’.

If you are looking for a specific sequence of w’s, like ‘www’, you would use w{3} to find occurrences of exactly 3 w’s. Adding a comma allows it to go beyond 3 as long there are at least 3. The ‘^’ denotes not, so [a-z] denotes any character from a-z, and [^a-z] denotes any character except those from a-z.

Comparators-

Comparators are a construct that allows designers to set a standard for comparison outside of the normal, or for things like custom objects. For example, if we had a program to determine the valedictorian of the class, we could have each student as an object. One of their characteristics would likely be GPA.

In this instance, we could provide a comparator that defines GPA as the determining order factor, rather than their names being alphabetized. Once this comparator is created, it can be used with the Collection.sort() or several of the tree type data structures.

To continue the student example, we would have a ‘Student’ class that had identifiers of student ID, GPA, and name at least. We could have much more like address and phone number if necessary. Then to create the comparator, we would create a new class, lets call it compareGPA, that implements the Comparator interface for our type <Student>. The comparator interface has two methods that should be overridden, compare and equals. In our example, ordering the students by GPA would look something like:

Public int compare(Student x, Student y){

If (y.getGPA() > y.getGPA()) //assuming several things like getter and setter methods

return Student x;

else return Student y;

}

We could also use this class to override the equals method. After creating all the structure of the comparator, we can use Collections.sort( List list, ‘Comparator constructor’ ). This will send an instance of that class to the sort method, meaning that we could also create other ones to compare them by location or student number if we wanted.

References:

Oracle

Previous
Previous

Java Review: Runnable Interface

Next
Next

Java Review: Sets & Maps