refactored Java code for speed