So, I have made a program to count words by occurrence, and print them by des order, also if the words have same frequency, they will be sorted alphabetically (also list contains Russian words, if the words have same frequency, the Russian words will go down from English words, and Russian words will be sorted Alphabetically as well).
if the word length is less then 4, or their frequency is less than 10, I want to remove them.
I need to check if word contains .,!? to remove them, and add them without those chars. For example:
hello!
will be addedhello
, orBye!
will be addedBye
Here is a good example for it:
лицами-18
Apex-15
azet-15
xder-15
анатолю-15
андреевич-15
батальона-15
hello-13
zello-13
полноте-13
Here is my code:
public String countWords(List<String> lines) {
StringBuilder input = new StringBuilder();
StringBuilder answer = new StringBuilder();
for (String line : lines){
if(line.length() > 3){
if(line.contains(",")){
line = line.replace(",", "");
input.append(line).append(" ");
}else if (line.contains(".")){
line = line.replace(".", "");
input.append(line).append(" ");
}else if (line.contains("!")){
line = line.replace("!", "");
input.append(line).append(" ");
}else if (line.contains("?")){
line = line.replace("?", "");
input.append(line).append(" ");
}else{
input.append(line).append(" ");
}
}
}
String[] strings = input.toString().split("\\s");
List<String> list = new ArrayList<>(Arrays.asList(strings));
Map<String, Integer> unsortMap = new HashMap<>();
while (list.size() != 0){
String word = list.get(0);
int freq = Collections.frequency(list, word);
if (word.length() >= 4 && freq >= 10){
unsortMap.put(word.toLowerCase(), freq);
}
list.removeAll(Collections.singleton(word));
}
List<String> sortedEntries = unsortMap.entrySet().stream()
.sorted(Comparator.comparingLong(Map.Entry<String, Integer>::getValue)
.reversed()
.thenComparing(Map.Entry::getKey)
)
.map(it -> it.getKey() + " - " + it.getValue())
.collect(Collectors.toList());
for (int i = 0; i < sortedEntries.size(); i++) {
if(i<sortedEntries.size()-1) {
answer.append(sortedEntries.get(i)).append("\n");
}
else{
answer.append(sortedEntries.get(i));
}
}
return answer.toString();
}
So, as you can see my code works fine. However, I want to go beyond this, and I want to write the same logic without using If, While, For. I want to write the same logic with streams or lambdas. As you can see I was able to write one part of the logic, to sort the list. However, I was not able to write the other parts where I have if and while loops. I am new to Streams and I want to know if there is some way I could write the same code, without using for, while, if statements, and only use streams.