VectorHelper { public static String vectorToJson(Vector vector, String[] dictionary, int maxEntries, boolean sort) { return buildJson(toWeightedTerms(sort ? topEntries(vector, maxEntries) : firstEntries(vector, maxEntries), dictionary)); } private  VectorHelper(); static String vectorToCSVString(Vector vector, boolean namesAsComments); static String buildJson(Iterable<Pair<String, Double>> iterable); static String buildJson(Iterable<Pair<String, Double>> iterable, StringBuilder bldr); static List<Pair<Integer, Double>> topEntries(Vector vector, int maxEntries); static List<Pair<Integer, Double>> firstEntries(Vector vector, int maxEntries); static List<Pair<String, Double>> toWeightedTerms(Collection<Pair<Integer, Double>> entries,
                                                           final String[] dictionary); static String vectorToJson(Vector vector, String[] dictionary, int maxEntries, boolean sort); static void vectorToCSVString(Vector vector,
                                       boolean namesAsComments,
                                       Appendable bldr); static String[] loadTermDictionary(File dictFile); static String[] loadTermDictionary(Configuration conf, String filePattern);  }
@Test public void testJsonFormatting() throws Exception { Vector v = new SequentialAccessSparseVector(10); v.set(2, 3.1); v.set(4, 1.0); v.set(6, 8.1); v.set(7, -100); v.set(9, 12.2); String UNUSED = "UNUSED"; String[] dictionary = { UNUSED, UNUSED, "two", UNUSED, "four", UNUSED, "six", "seven", UNUSED, "nine" }; assertEquals("sorted json form incorrect: ", "{nine:12.2,six:8.1,two:3.1}", VectorHelper.vectorToJson(v, dictionary, 3, true)); assertEquals("unsorted form incorrect: ", "{two:3.1,four:1.0}", VectorHelper.vectorToJson(v, dictionary, 2, false)); assertEquals("sorted json form incorrect: ", "{nine:12.2,six:8.1,two:3.1,four:1.0}", VectorHelper.vectorToJson(v, dictionary, 4, true)); assertEquals("sorted json form incorrect: ", "{nine:12.2,six:8.1,two:3.1,four:1.0,seven:-100.0}", VectorHelper.vectorToJson(v, dictionary, 5, true)); assertEquals("sorted json form incorrect: ", "{nine:12.2,six:8.1}", VectorHelper.vectorToJson(v, dictionary, 2, true)); assertEquals("unsorted form incorrect: ", "{two:3.1,four:1.0}", VectorHelper.vectorToJson(v, dictionary, 2, false)); }