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:

…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

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -