23 Java 8 File IO Part 2 PDF
23 Java 8 File IO Part 2 PDF
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
File Reading:
Second
Variation
Slides 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
9
Example 1: Printing All Palindromes
public class FileUtils {
public static void printAllPalindromes(Stream<String> words) {
words.filter(StringUtils::isPalindrome)
.forEach(System.out::println);
}
15
coreservlets.com custom onsite training
File Reading:
Third Variation
Slides 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Stream-processing method
Same as before: processes Stream<String>
File-processing method
Calls static method with two arguments:
Filename
Lambda designating the method that should get the Stream<String> that will come
from the file
18
We must define this static method. In order to pass in a method reference or explicit lambda here, the
method must take a functional (1-abstract-method) interface as its
second argument. We must define that interface, and its single method
must take a Stream<String>.
19
Variation 3: StreamProcessor Interface
@FunctionalInterface This is the single abstract method of the interface. Since it takes a Stream<String> as
argument, we can supply a method reference or lambda that refers to a method that
takes a Stream<String>, as with SomeClass::useStream on previous slide.
public interface StreamProcessor {
void processStream(Stream<String> strings);
20
21
Variation 2: Printing All Palindromes
public class FileUtils {
public static void printAllPalindromes(Stream<String> words) {
words.filter(StringUtils::isPalindrome)
.forEach(System.out::println);
}
23
Printing All Palindromes (Test Code)
public static void testAllPalindromes(String filename) {
List<String> testWords =
Arrays.asList("bog", "bob", "dam", "dad");
System.out.printf("All palindromes in list %s:%n", testWords);
FileUtils.printAllPalindromes(testWords.stream());
System.out.printf("All palindromes in file %s:%n", filename);
FileUtils.printAllPalindromes(filename);
}
Output
All palindromes in list [bog, bob, dam, dad]:
bob
dad
All palindromes in file enable1-word-list.txt:
aa
aba
...
24
25
Printing N-Length Palindromes (Test Code)
public static void testPalindromes(String filename, int... lengths) {
List<String> testWords =
Arrays.asList("rob", "bob", "reed", "deed");
for(int length: lengths) {
System.out.printf("%s-letter palindromes in list %s:%n",
length, testWords);
FileUtils.printPalindromes(testWords.stream(), length);
System.out.printf("%s-letter palindromes in file %s:%n",
length, filename);
FileUtils.printPalindromes(filename, length);
Output
} 3-letter palindromes in list [rob, bob, reed, deed]:
bob
} 3-letter palindromes in file enable1-word-list.txt:
aba
...
4-letter palindromes in list [rob, bob, reed, deed]:
deed
4-letter palindromes in file enable1-word-list.txt:
abba
26 ...
File Reading:
Fourth Variation
Slides 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Overview
Previous variation
Method that takes Stream<String> or Stream<T> and performs general Stream ops
No value returned
Method that takes filename, then calls static method with that filename and a
lambda or method reference designating the above method
This assumes that the above method has void return type
New variation
Method that takes Stream<String> or Stream<T> , performs general Stream ops,
and returns a value
Method that takes filename, then returns a value that is the result of calling a static
method with that filename and a lambda or method reference designating the above
method
This method now returns whatever the above method would return
29
Variation 4: General Approach
public static SomeType getValueFromStream(Stream<String> lines) {
return(lines.filter(...).map(...)...);
}
30
32
Output
First palindrome in list [bog, bob, dam, dad] is bob.
First palindrome in file enable1-word-list.txt is aa.
33
coreservlets.com custom onsite training
Advanced Option:
Combining Predicates
Slides 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
}
...
} @SafeVarargs is difficult to understand. The issue is that it is not always safe to use varargs for generic types: the resultant array can
have runtime type problems if you modify entries in it. But, if you only read the values and never modify them, varargs is perfectly safe.
@SafeVarargs says I am not doing anything dangerous, please suppress the compiler warnings.
For details, see http://docs.oracle.com/javase/8/docs/technotes/guides/language/non-reifiable-varargs.html
36
@SafeVarargs
public static Integer letterCount(String filename,
Predicate<String>... tests) {
return(StreamAnalyzer.analyzeFile(filename,
stream -> letterCount(stream, tests)));
}
37
Directly Applying Combiner (Test Code)
public static void testLetterCount(String filename) {
List<String> testWords = Arrays.asList("hi", "hello", "hola");
System.out.printf("In list %s:%n", testWords);
int sum1 = FileUtils.letterCount(testWords.stream(),
word -> word.contains("h"),
word -> !word.contains("i"));
printLetterCountResult(sum1, "contain h but not i");
System.out.printf("In file %s:%n", filename);
int sum2 = FileUtils.letterCount(filename, StringUtils::isPalindrome);
printLetterCountResult(sum2, "are palindromes");
int sum3 = FileUtils.letterCount(filename,
word -> word.contains("q"),
word -> !word.contains("qu"));
printLetterCountResult(sum3, "contain q but not qu");
int sum4 = FileUtils.letterCount(filename, word -> true);
printLetterCountResult(sum4, "are in English language");
}
39
Indirectly Applying Combiner: firstMatch
@SafeVarargs
public static <T> T firstMatch(Stream<T> elements,
Predicate<T>... tests) {
Predicate<T> combinedTest = FileUtils.combinedPredicate(tests);
return(elements.filter(combinedTest)
.findFirst()
.orElse(null));
}
@SafeVarargs
public static String firstMatch(String filename,
Predicate<String>... tests) {
return(StreamAnalyzer.analyzeFile(filename,
stream -> firstMatch(stream, tests)));
}
40
Applying firstMatch
public static void testFirstMatch(String filename) {
List<Integer> testNums = Arrays.asList(1, 10, 2, 20, 3, 30);
Integer match1 = FileUtils.firstMatch(testNums.stream(),
n -> n > 2,
n -> n < 10,
n -> n % 2 == 1);
System.out.printf("First word in list %s that is greater " +
"than 2, less than 10, and odd is %s.%n",
testNums, match1);
String match2 = FileUtils.firstMatch(filename,
word -> word.contains("q"),
word -> !word.contains("qu"));
System.out.printf("First word in file %s with q but " +
"not u is %s.%n", filename, match2);
}
Output
First word in list [1, 10, 2, 20, 3, 30] that is greater than 2, less than 10, and odd is 3.
41 First word in file enable1-word-list.txt with q but not u is buqsha.
Indirectly Applying Combiner: allMatches
@SafeVarargs
public static <T> List<T> allMatches(Stream<T> elements,
Predicate<T>... tests) {
Predicate<T> combinedTest = FileUtils.combinedPredicate(tests);
return(elements.filter(combinedTest)
.collect(Collectors.toList()));
}
@SafeVarargs
public static List<String> allMatches(String filename,
Predicate<String>... tests) {
return(StreamAnalyzer.analyzeFile(filename,
stream -> allMatches(stream, tests)));
}
42
Applying allMatches
public static void testAllMatches(String filename) {
List<Integer> testNums = Arrays.asList(2, 4, 6, 8, 10, 12);
List<Integer> matches1 = FileUtils.allMatches(testNums.stream(),
n -> n > 5,
n -> n < 10);
System.out.printf("All numbers in list %s that are " +
"greater than 5 and less than 10: %s.%n",
testNums, matches1);
List<String> matches2 = FileUtils.allMatches(filename,
word -> word.contains("q"),
word -> !word.contains("qu"));
System.out.printf("All words in file %s with q " +
"but not u: %s.%n", filename, matches2);
}
Output
All numbers in list [2, 4, 6, 8, 10, 12] that are greater than 5 and less than 10: [6, 8].
All words in file enable1-word-list.txt with q but not u: [buqsha, buqshas, faqir, ...].
43
coreservlets.com custom onsite training
Wrap-Up
Slides 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Summary
Variation 1 (last section)
Put all code inside main; main throws Exception
Simple and easy, but not reusable
Variation 2
Method 1 handles Stream; method 2 calls Files.lines and passes Stream to method 1
Reusable, but each version of method 2 repeats a lot of boilerplate code
Variation 3
Use lambdas to avoid the repetition
Variation 4
Use generic types so that values can be returned
Varargs for combining Predicates
Point: fancy Stream-processing becomes fancy file processing
45
coreservlets.com custom onsite training
Questions?
More info:
http://courses.coreservlets.com/Course-Materials/java.html General Java programming tutorial
http://www.coreservlets.com/java-8-tutorial/ Java 8 tutorial
http://courses.coreservlets.com/java-training.html Customized Java training courses, at public venues or onsite at your organization
http://coreservlets.com/ JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training
Slides 2016 Marty free
Many additional Hall, [email protected]
tutorials at coreservlets.com (JSF, Android, Ajax, Hadoop, and lots more)
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.