package com.google.sps.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Given a tweet or sentence, the servlet will extract salient terms
 * and store them in a list.
 */
@WebServlet("/keyword")
public class KeywordServlet extends HttpServlet {

  private static final List<String> tweets = new ArrayList<>();
  private static final List<String> terms = Arrays.asList("Black Lives Matter", "COVID-19");

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TODO: Extract saliency.
    String json = mustacheJsonBuilder(terms);
    response.getWriter().println(json);
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final String tweet = request.getParameter("keyword-sentence");
    if (tweet != null && !tweet.equals("")) {
      tweets.add(request.getParameter("keyword-sentence"));
    }
    response.sendRedirect("/index.html");
  }

  /**
   * Generates and returns a JSON usable by Mustache.
   */
  private String mustacheJsonBuilder(Collection<String> toJson) {
    String builder = "{\"keywords\": [";
    for (String term : toJson) {
      builder += String.format("{\"term\": \"%s\"},", term);
    }

    // Remove extra comma at the end.
    builder = builder.substring(0, builder.length() - 1) + "]}";
    return builder;
  }
}


@@ -836,25 +836,17 @@
  json = 
-mustacheJ
+j
 sonBuild
@@ -1326,17 +1326,9 @@
 ing 
-mustacheJ
+j
 sonB
@@ -1371,43 +1371,46 @@
     
+List%3C
 String
- builder = %22%7B%5C%22keywords%5C%22: %5B%22
+%3E terms = new ArrayList%3C%3E()
 ;%0A  
@@ -1450,61 +1450,44 @@
     
-builder += String.format(%22%7B%5C%22term%5C%22: %5C%22%25s%5C%22%7D,
+terms.add(keyValueJson(%22term
 %22, term)
 ;%0A  
@@ -1482,16 +1482,17 @@
 %22, term)
+)
 ;%0A    %7D%0A
@@ -1538,87 +1538,324 @@
     
-builder = builder.substring(0, builder.length() - 1) + %22%5D%7D%22;
+String keywordPrefix = %22%7B%5C%22keywords%5C%22: %5B%22;%0A    return String.format(keywordPrefix + %22%25s%5D%7D%22, String.join(%22,%22, terms));%0A  %7D%0A%0A  /**%0A   * Given a key-value pair, this function returns %22%7Bkey: value%7D%22.
 %0A   
- return builder
+*/%0A  private String keyValueJson(String key, String value) %7B%0A    return String.format(%22%7B%5C%22%25s%5C%22: %5C%22%25s%5C%22%7D%22, key, value)
 ;%0A  

Change to String.join(), change json builder method title