Given a song, write an algorithm that displays the lyrics with the most repetitions, that is, the most frequent lyrics. If several words have the same number of repetitions, then the algorithm will display only the word which has the greatest number of characters.
For example, in the following song:
"Hate me today",
"Hate me tomorrow",
"Hate me for all the things I didn't do for you",
"Hate me in ways",
"Yeah, ways hard to swallow",
"Hate me so you can finally see what's good for you",
"Hate me today",
"Hate me tomorrow",
"Hate me for all the things I didn't do for you",
"Hate me in ways",
"Yeah, ways hard to swallow",
"Hate me so you can finally see what's good for you",
"Hate me today",
"Hate me tomorrow",
"Hate me for all the things I didn't do for you",
"Hate me in ways",
"Yeah, ways hard to swallow",
"Hate me so you can finally see what's good for you",
"For you",
"For you",
"For you"
I have tried something and it returns me the most word repeated. But the problem is how to get the word which has the greatest number of characters.
This is my code :
public class Main {
/* The name of the class has to be Main. */
public static void main(String[] args) {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))){
List<String> lyrics = new LinkedList<>();
while(bufferedReader.ready()) {
lyrics.add(bufferedReader.readLine());
}
/* YOUR CODE HERE */
String mostRepeatedWord
= lyrics.stream()
.map(word -> word.toUpperCase())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(x -> x.getKey().length() > 0)
.max(Comparator.comparing(Entry::getValue))
.get()
.getKey();
System.out.println(mostRepeatedWord);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Without JAVA 8 this solution works perfectly but i want it with JAVA 8
public class Main {
/* The name of the class has to be Main. */
public static void main(String[] args) {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))){
List<String> lyrics = new LinkedList<>();
while(bufferedReader.ready()) {
lyrics.add(bufferedReader.readLine());
}
Map<String, Integer> stringsCount = new HashMap<String, Integer>();
for(String string: lyrics)
{
if (string.length() > 0) {
string = string.replace(",","!");
Integer count = stringsCount.get(string);
if(count == null) count = new Integer(0);
count++;
stringsCount.put(string,count);
}
}
Map.Entry<String,Integer> mostRepeated = null;
for(Map.Entry<String, Integer> e: stringsCount.entrySet())
{
if(mostRepeated == null || mostRepeated.getValue()<e.getValue())
mostRepeated = e;
}
String result = mostRepeated.getKey().replace("!",",");
System.out.println(result.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks for the help !!!