Skip to content

Instantly share code, notes, and snippets.

@samiraghayarov
Created April 28, 2021 14:37
Show Gist options
  • Save samiraghayarov/072ffe5006db2ec5f257c08d7ef49ed8 to your computer and use it in GitHub Desktop.
Save samiraghayarov/072ffe5006db2ec5f257c08d7ef49ed8 to your computer and use it in GitHub Desktop.
package com.octagon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ApplicationMain {
private static final String DELIMITER = " ";
public static void main(String[] args) throws URISyntaxException, IOException {
Set<String> stopwords = new HashSet<>();
Set<String> fileNames = new HashSet<>();
Boolean upperCaseFlag = Boolean.FALSE;
for (int i = 0; i < args.length; i += 2) {
if ("-F".equals(args[i])) {
fileNames = paramsToSet(args[i + 1]);
System.out.println(fileNames);
} else if ("-S".equals(args[i])) {
stopwords = paramsToSet(args[i + 1]);
System.out.println(stopwords);
} else if ("-L".equals(args[i])) {
upperCaseFlag = Boolean.TRUE;
System.out.println(upperCaseFlag);
}
}
for (String fileName : fileNames) {
int count = countWords(stopwords, upperCaseFlag, fileName);
System.out.printf("%s has %d words , stopwordsFlag %b , upperCaseFlag %b", fileName, count,
!stopwords.isEmpty(), upperCaseFlag);
}
}
private static Set<String> paramsToSet(String arg) {
return Arrays.stream(arg.split(","))
.collect(Collectors.toSet());
}
private static int countWords(Set<String> stopwords, Boolean upperCaseFlag, String fileName) throws IOException, URISyntaxException {
Stream<String> lines = readFile(fileName);
//flattened words
List<String> words = lines.flatMap(line -> Arrays.stream(line.trim().split(DELIMITER)))
.filter(word -> isStopWord(word, stopwords))
.filter(word -> isUpperCase(word, upperCaseFlag))
.collect(Collectors.toList());
return words.size();
}
public static Stream<String> readFile(String fileName) throws IOException, URISyntaxException {
InputStream resource = ApplicationMain.class.getClassLoader().getResourceAsStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(
resource,
StandardCharsets.UTF_8
);
return new BufferedReader(inputStreamReader).lines();
}
private static boolean isUpperCase(String word, boolean upperCaseFlag) {
if (!upperCaseFlag) return true;
return !word.isEmpty() && Character.isUpperCase(word.charAt(0));
}
private static boolean isStopWord(String word, Set<String> stopwords) {
return !word.isEmpty() && !stopwords.contains(word);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment