Read words/phrases from a file, make distinct, and write out to another file, in Java -
i have text file word or phrase on each line. how i:
- read phrases memory,
- make distinct (eliminate duplicates),
- sort alphabetically,
- write results out file?
stackoverflow has answers similar questions in other languages such c, php, python, prolog, , vb6. cannot find 1 java.
you can leverage:
- nio (non-blocking i/o) api (available since java 7)
- streams api (available since java 8)
…to solve problem elegantly:
public static void main(string... args) { path input = paths.get("/users/youruser/yourinputfile.txt"); path output = paths.get("/users/youruser/youroutputfile.txt"); try { list<string> words = getdistinctsortedwords(input); files.write(output, words, utf_8); } catch (ioexception e) { //log error and/or warn user } } private static list<string> getdistinctsortedwords(path path) throws ioexception { try(stream<string> lines = files.lines(path, utf_8)) { return lines.map(string::trim) .filter(s -> !s.isempty()) // if keyword not empty, collect it. .distinct() .sorted() .collect(tolist()); } }
note: requires static imports
import static java.nio.charset.standardcharsets.utf_8; import static java.util.stream.collectors.tolist;
Comments
Post a Comment