Skip to content

Instantly share code, notes, and snippets.

@brycetshaw
Last active August 16, 2020 17:09
Show Gist options
  • Save brycetshaw/8d57e87e56b81b3a94c993df791f5b0c to your computer and use it in GitHub Desktop.
Save brycetshaw/8d57e87e56b81b3a94c993df791f5b0c to your computer and use it in GitHub Desktop.
Parses a list of words, sorts lexicographically, and groups words that are anagrams. Today I learned how to use the streams API and the word "lexicographic".
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class AnagramFinder {
public static void parseAnagrams(Stream<String> inStream, Writer pw) {
inStream
.sorted() // Sort input words lexicographically
.collect(Collectors.groupingBy(word -> Stream.of(word // GroupBy -> Map of key<String> value<List> pairs
.split("")) // Split word into Array of chars
.sorted() // Sort array of chars
.collect(Collectors.joining()))) //Map key -> sortedString | value -> List of anagrams
.forEach((key, value) -> { // for each (key, value) pair in the Hash Map...
try {
pw.append(value.stream() //join value<list> eleements, with "," separator, write out
.collect(Collectors.joining(",")))
.append("\n"); //Add \n after every (key, value) pair.
} catch (IOException e) {
e.printStackTrace();
}
});
}
public static void main(String[] args) {
String pathToCSV = "/home/bryce/Workspace/MENG/anagrams-finder/src/com/company/";
String fileName = "words.csv";
String outputFileName = "output.csv";
try ( //Try-with-resource: Closes all resources that implement AutoClosable feature
PrintWriter pw = new PrintWriter(new File(pathToCSV + outputFileName));
Stream<String> inStream = Files.lines(Paths.get(pathToCSV.concat(fileName)));
) {
parseAnagrams(inStream, pw);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.StringWriter;
import java.util.Arrays;
import java.util.stream.Stream;
import static com.company.AnagramFinder.parseAnagrams;
import static org.junit.jupiter.api.Assertions.*;
class AnagramFinderTest {
@org.junit.jupiter.api.Test
void testParseAnagrams() {
Stream<String> inStream = Arrays.stream(new String[]
{
"car",
"dog",
"bed",
"stop",
"god",
"pots",
"arc",
"tops"
});
String expected =
"arc,car\n" +
"bed\n" +
"pots,stop,tops\n" +
"dog,god\n";
StringWriter stringWriter = new StringWriter();
parseAnagrams(inStream, stringWriter);
assertEquals(expected, stringWriter.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment