Question

In: Computer Science

Java Question I have a Queue containing String type taking in a text file with an...

Java Question

I have a Queue containing String type taking in a text file with an iterator.

I need to use ArrayList and HashMap for freqHowMany to get a frequency table in descending order by the highest frequency words in the text. Any help would be much appreciated and thanks!

final Iterator input = new Scanner(System.in).useDelimiter("(?U)[^\\p{Alpha}0-9']+");
        final Queue queueFinal = new CircularFifoQueue<>(wordsLast);

        while (input.hasNext()) {
            final String queueWord = input.next();
            if (queueWord.length() > minimumLength) {
                queueFinal.add(queueWord); // the oldest item automatically gets evicted
            }

            System.out.println(queueFinal);
        }
    }
}

EXAMPLE:

Your program prints an updated word cloud for each sufficiently long word read from the standard input.

The program takes up to three positive command-line arguments:

  • freqHowMany indicates the size of the word cloud, i.e., the number of words in descending order of frequency to be shown
  • wordMinLength indicates the minimum length of a word to be considered; shorter words are ignored
  • wordLastNwords indicates the size of a moving window of n most recent words of sufficient length for which to update the word cloud

Your program then reads a continuous stream of words, separated by whitespace or other non-word characters, from the standard input. (A word can have letters, numbers, or single quotes.) For each word read, your program prints to standard output, on a single line, a textual representation of the word cloud of the form

The idea is to connect this tool to a streaming data source, such as Twitter, or speech-to-text from a 24-hour news channel, and be able to tell from the word cloud in real time what the current "hot" topics are.

THANKS!

Solutions

Expert Solution

There are two ways to handle this.

1) Use a TreeMap which is sorted by values. In this way, you would get the words in the descending order of frequency.

Sample code:

import java.util.*;

public class SortMap {
    public static <K, V extends Comparable<V>> Map<K, V>
    sortByValues(final Map<K, V> map) {
        Comparator<K> valueComparator =
                new Comparator<K>() {
                    public int compare(K k1, K k2) {
                        return map.get(k2).compareTo(map.get(k1));
                    }
                };

        Map<K, V> sortedByValues =
                new TreeMap<K, V>(valueComparator);
        sortedByValues.putAll(map);
        return sortedByValues;
    }


public static void main(String[] args) {        
Queue<String> q = new LinkedList<>();
q.add("a");
q.add("b");
q.add("c");
q.add("b");
q.add("b");
q.add("b");
q.add("b");
q.add("c");
q.add("c");
HashMap<String, Integer> map = new HashMap<>();
while (!q.isEmpty()) {
    map.put(q.peek(), map.getOrDefault(q.poll(), 0) + 1);
}
        TreeMap<String, Integer> sortedMap = (TreeMap<String, Integer>) sortByValues(map);
        sortedMap.keySet().stream().forEach(k -> System.out.println(k+"->"+sortedMap.get(k)));
    }
}

Output:

b->5
c->3
a->1


2) Since the frequency of words is what matters, we can transfer the HashMap<String, Integer> to a TreeMap<Integer, String> which sorts the table in descending order of frequency (i.e.) store the key of HashMap as value and value of HashMap as key.
Sample code:

import java.util.*;

public class SortMap {

public static void main(String[] args) {
Queue<String> q = new LinkedList<>();
q.add("a");
q.add("b");
q.add("c");
q.add("b");
q.add("b");
q.add("b");
q.add("b");
q.add("c");
q.add("c");
HashMap<String, Integer> map = new HashMap<>();
while (!q.isEmpty()) {
    map.put(q.peek(), map.getOrDefault(q.poll(), 0) + 1);
}
        TreeMap<Integer, String> sortedMap = new TreeMap<>((v1,v2) -> (v2 - v1));
        map.keySet().stream().forEach(k -> sortedMap.put(map.get(k), k));
        sortedMap.keySet().stream().forEach(k -> System.out.println(k+"->"+sortedMap.get(k)));
    }
}

Output:

b->5
c->3
a->1


Related Solutions

Java - Text File to Arrays and output ------------------------------------------------------------------------------ I need to have a java program...
Java - Text File to Arrays and output ------------------------------------------------------------------------------ I need to have a java program read an "input.txt" file (like below) and store the information in an respective arrays. This input.txt file will look like below and will be stored in the same directory as the java file. The top line of the text represents the number of people in the group for example. the lines below it each represent the respective persons preferences in regards to the other...
Read a text file into arrays and output - Java Program ------------------------------------------------------------------------------ I need to have...
Read a text file into arrays and output - Java Program ------------------------------------------------------------------------------ I need to have a java program read an "input.txt" file (like below) and store the information in an respective arrays. This input.txt file will look like below and will be stored in the same directory as the java file. The top line of the text represents the number of people in the group for example. the lines below it each represent the respective persons preferences in regards...
Part I The input to the program will be a text file containing the information for...
Part I The input to the program will be a text file containing the information for a tolerance table. An example follows using the values from the first lecture on tolerance analysis. These values will be stored in a text file. The data is comma delimited, which means that each data field is separated by a comma. If the first word is ‘PART’ the following values are the nominal size, +/- impact, tolerance, and fixed/variable. If the first word is...
Java Code using Queue Write a program that opens a text file and reads its contents...
Java Code using Queue Write a program that opens a text file and reads its contents into a queue of characters, it should read character by character (including space/line change) and enqueue characters into a queue one by one. Dequeue characters, change their cases (upper case to lower case, lower case to upper case) and save them into a new text file (all the chars are in the same order as the original file, but with different upper/lower case) use...
This is a java coding String manipulation Question. Let us say I have a String which...
This is a java coding String manipulation Question. Let us say I have a String which looks something likes this: String x = "MATH,PHYSICS,CHEMISTRY,CODING" And then I have another String which looks something like this: String y = "XXXXMXXXAXXXTXXXXHXXXXXXCXXXXOXXXXDXXXIXXXXNXXXGXXXX" and another String that looks like this: String z = "XXXXHXXTXXXXAXXMXXXXXCXXXOXXXDXXXIXXXNXXXG" I want to take String y and print the words that are found in String x as such: Math Coding and for String z if I want to take it...
Left shift. I am trying to left shift a string located in a text file. I...
Left shift. I am trying to left shift a string located in a text file. I am using c++ and the goal is to left shift by 1 character a string of length N, and output on stdout all of the performed shifts. Can someone tell me what I am doing wrong, and tell me what I can fix? i.e: text file contains: Hi there!. Output on stdout: Hi there!, i there!H, _there!Hi, there!Hi_,...., !Hi_there. #here "_" represent space. -------------------------------------------------------------------------------------------------------------------------...
Allow the main process to generate a text file containing the text of this assignment. The...
Allow the main process to generate a text file containing the text of this assignment. The main process will then create two other processes and pass to them the name of the file and two codes (code1 and code2) using a pipe() system call. The codes are two different alphabetic letters such as “a” and “k”. The child processes should search the file for the character in the interval received, compute their frequencies and return them through a separate pipe...
JAVA: Implement a Queue ADT using a circular array with 5 string elements. Create a Queue...
JAVA: Implement a Queue ADT using a circular array with 5 string elements. Create a Queue object and try various operations below. Queue myQueue = new Queue(); myQueue.enqueue(“CPS 123”); myQueue.enqueue(“CPS 223”); myQueue.enqueue(“CPS 323”); myQueue.dequeue(); myQueue.enqueue(“CPS 113”); myQueue.enqueue(“CPS 153”); string course = myQueue.front(); // course should be CPS 223 size = myQueue.size(); // size should be 4 // output course and size
I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
#Java I am reading from the txt file and I put everytihng inside of the String[],...
#Java I am reading from the txt file and I put everytihng inside of the String[], like that: String[] values = str.split(", "); But, now I have to retrieve the data from it one by one. How can I do it? Here is the txt file: OneTime, finish the project, 2020-10-15 Monthly, wash the car, 2020-11-10 Thanks!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT