title: Find second to last word in multi-lined string array
body: <p>I need to find second to last word in each line (they are divided by space) and find 3 most popular of them and find how many are there? Can you help me in any way?</p>
  
  <p>Input example:</p>
  
  <pre><code>abcd i
  asd ffdds abcd ddd ?
  abcd ffdds asd ddd i
  ddd abcd i
  a f g w e a asdfasdasdas fdd i
  </code></pre>
  
  <p>Answer that I need: </p>
  
  <pre><code>abcd 2
  ddd 2
  fdd 1
  </code></pre>
  
  <p>or</p>
  
  <pre><code>2 abcd
  2 ddd
  1 fdd
  </code></pre>
  
  <p>This is my code</p>
  
  <pre><code>public class asdf {
  
      public static void main(String args[]) throws IOException {
          BufferedReader in = new BufferedReader(new FileReader("input.txt"));
          String str;
  
          List &lt; String &gt; list = new ArrayList &lt; String &gt; ();
          while ((str = in .readLine()) != null) {
              if (str.startsWith(" ") &amp;&amp; str.endsWith("i") || str.endsWith("?")) {
  
                  list.add(str);
              }
          }
          String[] stringArr = list.toArray(new String[0]); //for backup
          String[] stringArrAC = list.toArray(new String[0]);
  
          for (int i = 0; i &lt; stringArrAC.length; i++) {
              stringArrAC[i] = stringArrAC[i].substring(63);
          }
          //String[] stringArrLAST = (new String[0]);
           Map&lt;String, Integer&gt; occurrences = new HashMap();
          for (String line : stringArrAC) {
              String[] words = line.split(" ");
              String nextToLastWord = words[words.length - 2];
              occurrences.put(nextToLastWord, 
                      occurrences.get(nextToLastWord) == null 
                              ? 1 
                              : occurrences.get(nextToLastWord) + 1); 
          }
  
          occurrences.entrySet().stream()
              // Sort the values in descending order
              .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
              // Gets top 3 entries
              .limit(3)
              // Print them 
              .forEach(System.out::println);
          try {
              PrintWriter pr = new PrintWriter("output.txt");
              for (int i = 0; i &lt; stringArrAC.length; i++) {
                  pr.println(stringArrAC[i]);
              }
              pr.close();
          } catch (Exception e) {
              e.printStackTrace();
              System.out.println("No such file exists.");
          }
      }
  </code></pre>