public static boolean anagram(String input) { int numOdd = 0; int count = 0; char[] chars = input.toLowerCase().toCharArray(); ArrayList<Character> letters = new ArrayList<Character>(); for (int i = 0; i < chars.length; i++) { for (int j = 0; j < chars.length; j++) { if (chars[i] == chars[j] && !letters.contains(chars[i])) { count++; } } if (!letters.contains(chars[i])) { letters.add(chars[i]); } if (count % 2 == 1) { numOdd++; } count = 0; } if (input.length() % 2 == 0 && numOdd > 0) { return false; } else if (numOdd > 1) { return false; } else { return true; } }
public static boolean isBlockInList(HashMap<Integer, ArrayList<Integer>> map, int id, int meta) { ArrayList<Integer> list = map.get(id); if (list == null) { return false; } return list.contains(meta) || list.contains(-1); }
public ArrayList<String> collectLinks(String p) { ArrayList<String> PageLinks = new ArrayList<String>(); try { URL url = new URL(p); BufferedReader br3 = new BufferedReader(new InputStreamReader(url.openStream())); String str = ""; while (null != (str = br3.readLine())) { Pattern link = Pattern.compile( "<a target=\"_top\" href=\"/m/.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher match = link.matcher(str); while (match.find()) { String tmp = match.group(); int start = tmp.indexOf('/'); tmp = tmp.substring(start + 1, tmp.indexOf('\"', start + 1)); if (Crawl.contains("http://www.rottentomatoes.com/" + tmp) || ToCrawl.contains("http://www.rottentomatoes.com/" + tmp) || PageLinks.contains("http://www.rottentomatoes.com/" + tmp)) continue; PageLinks.add("http://www.rottentomatoes.com/" + tmp); // bw4.write("http://www.rottentomatoes.com/"+tmp+"\r\n"); } } br3.close(); } catch (Exception ex) { ex.printStackTrace(); } return PageLinks; }
/** Values.toArray contains all values */ public void testDescendingValuesToArray() { ConcurrentNavigableMap map = dmap5(); Collection v = map.values(); Object[] ar = v.toArray(); ArrayList s = new ArrayList(Arrays.asList(ar)); assertEquals(5, ar.length); assertTrue(s.contains("A")); assertTrue(s.contains("B")); assertTrue(s.contains("C")); assertTrue(s.contains("D")); assertTrue(s.contains("E")); }
private Card genNewCard() { Random rand = new Random(); Card card = new Card(rand.nextInt(52) + 1); while (cardUsed.contains(card)) card = new Card(rand.nextInt(52) + 1); cardUsed.add(card); return card; }
public static void main(String[] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader("badrand.in")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("badrand.out"))); // Use StringTokenizer vs. readLine/split -- lots faster StringTokenizer st = new StringTokenizer(f.readLine()); // Get line, break into tokens int i1 = Integer.parseInt(st.nextToken()); // first integer ArrayList squares = new ArrayList<Integer>(10000); int mark = 0; i1 = middleSquare(i1); while (i1 > 0) { if (squares.contains(i1)) { squares.add(i1); squares.set(squares.indexOf(i1), 10000); mark = i1; i1 = 0; } else { squares.add(i1); i1 = middleSquare(i1); } } squares.add(10000); squares.add(0); out.println(squares.indexOf(mark) + 1); out.close(); // close the output file System.exit(0); // don't omit this! }
// Deze method checkt rooster conflicten (Dubbele roosteringen van studenten) public int computeStudentConflicts() { ArrayList<Student> checkedStudentsList = new ArrayList<Student>(); int studentConflictCounter = 0; boolean conflictFound = false; for (int i = 0; i < timeslots; i++) { for (int j = 0; j < rooms.size() - 1; j++) { Activity activity = rooms.get(j).timetable.get(i); if (activity != null) { for (Student student : activity.studentGroup) { if (!checkedStudentsList.contains(student)) { for (int k = j + 1; k < rooms.size(); k++) { Room otherRoom = rooms.get(k); Activity otherActivity = otherRoom.timetable.get(i); if (otherActivity != null) { if (otherActivity.studentGroup.contains(student)) { studentConflictCounter++; conflictFound = true; } } } } if (conflictFound) { checkedStudentsList.add(student); conflictFound = false; } } } } checkedStudentsList.clear(); } return studentConflictCounter; }
/** * Adds the given <tt>FileTransferListener</tt> that would listen for file transfer requests and * created file transfers. * * @param listener the <tt>FileTransferListener</tt> to add */ public void addFileTransferListener(FileTransferListener listener) { synchronized (fileTransferListeners) { if (!fileTransferListeners.contains(listener)) { this.fileTransferListeners.add(listener); } } }
private void updateRecord(DataRecord r, ArrayList<String> fieldsInInport) { try { DataRecord rorig = (versionized ? dataAccess.getValidAt(r.getKey(), validAt) : dataAccess.get(r.getKey())); if (rorig == null) { logImportFailed( r, International.getString("Keine gültige Version des Datensatzes gefunden."), null); return; } // has the import record an InvalidFrom field? long invalidFrom = (versionized ? getInvalidFrom(r) : -1); if (invalidFrom <= rorig.getValidFrom()) { invalidFrom = -1; } boolean changed = false; for (int i = 0; i < fields.length; i++) { Object o = r.get(fields[i]); if ((o != null || fieldsInInport.contains(fields[i])) && !r.isKeyField(fields[i]) && !fields[i].equals(DataRecord.LASTMODIFIED) && !fields[i].equals(DataRecord.VALIDFROM) && !fields[i].equals(DataRecord.INVALIDFROM) && !fields[i].equals(DataRecord.INVISIBLE) && !fields[i].equals(DataRecord.DELETED)) { Object obefore = rorig.get(fields[i]); rorig.set(fields[i], o); if ((o != null && !o.equals(obefore)) || (o == null && obefore != null)) { changed = true; } } } if (invalidFrom <= 0) { long myValidAt = getValidFrom(r); if (!versionized || updMode.equals(UPDMODE_UPDATEVALIDVERSION) || rorig.getValidFrom() == myValidAt) { if (changed) { dataAccess.update(rorig); } setCurrentWorkDone(++importCount); } if (versionized && updMode.equals(UPPMODE_CREATENEWVERSION) && rorig.getValidFrom() != myValidAt) { if (changed) { dataAccess.addValidAt(rorig, myValidAt); } setCurrentWorkDone(++importCount); } } else { dataAccess.changeValidity(rorig, rorig.getValidFrom(), invalidFrom); setCurrentWorkDone(++importCount); } } catch (Exception e) { logImportFailed(r, e.toString(), e); } }
public boolean isMod(String sender) { if (mods.contains(sender)) { return true; } else { return false; } }
public boolean isAdmin(String sender) { if (admins.contains(sender)) { return true; } else { return false; } }
private void oddPoint(ArrayList<Integer> oddPoints, int from) { if (oddPoints.contains(from)) { oddPoints.remove(new Integer(from)); } else { oddPoints.add(from); } }
protected void writeAuditTrail(String strPath, String strUser, StringBuffer sbValues) { BufferedReader reader = WFileUtil.openReadFile(strPath); String strLine; ArrayList aListData = WUtil.strToAList(sbValues.toString(), false, "\n"); StringBuffer sbData = sbValues; String strPnl = (this instanceof DisplayTemplate) ? "Data Template " : "Data Dir "; if (reader == null) { Messages.postDebug("Error opening file " + strPath); return; } try { while ((strLine = reader.readLine()) != null) { // if the line in the file is not in the arraylist, // then that line has been deleted if (!aListData.contains(strLine)) WUserUtil.writeAuditTrail(new Date(), strUser, "Deleted " + strPnl + strLine); // remove the lines that are also in the file or those which // have been deleted. aListData.remove(strLine); } // Traverse through the remaining new lines in the arraylist, // and write it to the audit trail for (int i = 0; i < aListData.size(); i++) { strLine = (String) aListData.get(i); WUserUtil.writeAuditTrail(new Date(), strUser, "Added " + strPnl + strLine); } reader.close(); } catch (Exception e) { e.printStackTrace(); } }
private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException { if (processedLinks.contains(url)) { return false; } else { processedLinks.add(url); } URLConnection connection = url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); ArrayList list = processPage(in, baseDir, url); if ((status != null) && (list.size() > 0)) { status.setMaximum(list.size()); } for (int i = 0; i < list.size(); i++) { if (status != null) { status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i); } if ((!((String) list.get(i)).startsWith("RUN")) && (!((String) list.get(i)).startsWith("SAVE")) && (!((String) list.get(i)).startsWith("LOAD"))) { processURL( new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)), baseDir, status); } } in.close(); return true; }
private int initializeBuilder(int kind, boolean forBuild) throws CoreException { // some calls just need the nameEnvironment initialized so skip the rest this.javaProject = (JavaProject) JavaCore.create(this.currentProject); this.workspaceRoot = this.currentProject.getWorkspace().getRoot(); if (forBuild) { // cache the known participants for this project this.participants = JavaModelManager.getJavaModelManager() .compilationParticipants .getCompilationParticipants(this.javaProject); if (this.participants != null) for (int i = 0, l = this.participants.length; i < l; i++) if (this.participants[i].aboutToBuild(this.javaProject) == CompilationParticipant.NEEDS_FULL_BUILD) kind = FULL_BUILD; // Flush the existing external files cache if this is the beginning of a build cycle String projectName = this.currentProject.getName(); if (builtProjects == null || builtProjects.contains(projectName)) { builtProjects = new ArrayList(); } builtProjects.add(projectName); } this.binaryLocationsPerProject = new SimpleLookupTable(3); this.nameEnvironment = new NameEnvironment( this.workspaceRoot, this.javaProject, this.binaryLocationsPerProject, this.notifier); if (forBuild) { String filterSequence = this.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true); char[][] filters = filterSequence != null && filterSequence.length() > 0 ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { this.extraResourceFileFilters = null; this.extraResourceFolderFilters = null; } else { int fileCount = 0, folderCount = 0; for (int i = 0, l = filters.length; i < l; i++) { char[] f = filters[i]; if (f.length == 0) continue; if (f[f.length - 1] == '/') folderCount++; else fileCount++; } this.extraResourceFileFilters = new char[fileCount][]; this.extraResourceFolderFilters = new String[folderCount]; for (int i = 0, l = filters.length; i < l; i++) { char[] f = filters[i]; if (f.length == 0) continue; if (f[f.length - 1] == '/') this.extraResourceFolderFilters[--folderCount] = new String(f, 0, f.length - 1); else this.extraResourceFileFilters[--fileCount] = f; } } } return kind; }
// specify input and out keys public void map( LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { String line = value.toString(); // define new variable to be string ArrayList<Integer> range = new ArrayList<Integer>(); for (int i = 2000; i <= 2010; i++) { range.add(i); } // String[] inputs = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); String[] inputs = line.split(","); try { int year = Integer.parseInt(inputs[165]); if (range.contains(year)) { String dur = inputs[3]; String artist_name = inputs[2]; String song_title = inputs[1]; String final_input = artist_name + ',' + dur + ',' + song_title; Final_Value.set(final_input); output.collect(Final_Value, dummy); } } catch (NumberFormatException e) { // do nothing } }
boolean isExcluded(String name) { if (m_propertyExcludeList != null) { if (m_propertyExcludeList.contains(name)) { return true; } } // end if return false; } // end isExcluded
protected boolean findSourceFiles(IResourceDelta delta) throws CoreException { ArrayList visited = this.makeOutputFolderConsistent ? new ArrayList(this.sourceLocations.length) : null; for (int i = 0, l = this.sourceLocations.length; i < l; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; if (this.makeOutputFolderConsistent && md.hasIndependentOutputFolder && !visited.contains(md.binaryFolder)) { // even a project which acts as its own source folder can have an independent/nested output // folder visited.add(md.binaryFolder); IResourceDelta binaryDelta = delta.findMember(md.binaryFolder.getProjectRelativePath()); if (binaryDelta != null) { int segmentCount = binaryDelta.getFullPath().segmentCount(); IResourceDelta[] children = binaryDelta.getAffectedChildren(); for (int j = 0, m = children.length; j < m; j++) if (!checkForClassFileChanges(children[j], md, segmentCount)) return false; } } if (md.sourceFolder.equals(this.javaBuilder.currentProject)) { // skip nested source & output folders when the project is a source folder int segmentCount = delta.getFullPath().segmentCount(); IResourceDelta[] children = delta.getAffectedChildren(); for (int j = 0, m = children.length; j < m; j++) if (!isExcludedFromProject(children[j].getFullPath())) if (!findSourceFiles(children[j], md, segmentCount)) return false; } else { IResourceDelta sourceDelta = delta.findMember(md.sourceFolder.getProjectRelativePath()); if (sourceDelta != null) { if (sourceDelta.getKind() == IResourceDelta.REMOVED) { if (JavaBuilder.DEBUG) System.out.println( "ABORTING incremental build... found removed source folder"); //$NON-NLS-1$ return false; // removed source folder should not make it here, but handle anyways // (ADDED is supported) } int segmentCount = sourceDelta.getFullPath().segmentCount(); IResourceDelta[] children = sourceDelta.getAffectedChildren(); try { for (int j = 0, m = children.length; j < m; j++) if (!findSourceFiles(children[j], md, segmentCount)) return false; } catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an // as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println( "ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow } } } this.notifier.checkCancel(); } return true; }
/** * Metodo que verifica los argumentos pasados al programa * * @param indice Indice del arreglo de argumentos * @param longitud Longitud del arreglo de argumentos * @param args Arreglo de argumentos * @param listaFlags lista con los flags validos */ private static void verificarArg( int indice, int longitud, String[] args, ArrayList<String> listaFlags) { if ((indice + 1 == longitud) || listaFlags.contains(args[indice + 1])) { System.out.println( "- ERROR - Sintaxis: java c_rmifs [-f usuarios] -p puerto -m servidor [-c comandos]"); System.exit(EXIT_FAILURE); } }
public static Hashtable find_combos(Hashtable table, ArrayList<User> users, int r_value) { ArrayList<Integer> combinations = new ArrayList<Integer>(); ArrayList<List<Integer>> combvalues = new ArrayList<List<Integer>>(); // System.out.println("current hash "+table); Iterator iter = table.keySet().iterator(); while (iter.hasNext()) { ArrayList<Integer> hashvalue = (ArrayList<Integer>) iter.next(); // System.out.println(hashvalue+"::value with support "+table.get(hashvalue)); if ((Integer) table.get(hashvalue) >= MINSUP) { combinations.add((Integer) table.get(hashvalue)); combvalues.add(hashvalue); } } // System.out.println("combinations that survive: "+combvalues); ArrayList<Integer> unique_combo_values = new ArrayList<Integer>(); for (int i = 0; i < combvalues.size(); i++) { for (int k = 0; k < combvalues.get(i).size(); k++) { if (!unique_combo_values.contains(combvalues.get(i).get(k))) { unique_combo_values.add(combvalues.get(i).get(k)); } } } ArrayList<List<Integer>> new_combos = new ArrayList<List<Integer>>(); new_combos = (ArrayList<List<Integer>>) combinations(unique_combo_values, r_value); // System.out.println("generated new combinations: "+new_combos); Hashtable t = new Hashtable(); for (int j = 0; j < new_combos.size(); j++) { for (int i = 1; i <= num_users; i++) { if (users.get(i).hasSameNumbers((new_combos.get(j)))) { if (t.containsKey(new_combos.get(j))) { int count = (Integer) t.get(new_combos.get(j)); count++; t.put(new_combos.get(j), count); // System.out.println("added one to "+new_combos.get(j)); } else { t.put(new_combos.get(j), 1); // System.out.println("set to 1"+new_combos.get(j)); } } } } // System.out.println("before weeding "+t); Iterator final_iter = t.keySet().iterator(); while (final_iter.hasNext()) { ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next(); // System.out.println("current support of "+ next+ " is "+t.get(next)); // System.out.println(MINSUP); if ((Integer) t.get(next) < MINSUP || next.isEmpty()) { // System.out.println("hi"); final_iter.remove(); } } return t; }
// if propertyName is in excludeList, or if className is in excludeList // className : like 'Table', 'Column', 'Class', .. // propertyName : like 'Table.Name', 'Column.Alias', .. protected boolean verifyExclusion(String className, String propertyName, RuleOptions options) { boolean excluded = false; if (options == null) { return false; } ArrayList excludeList = options.getExcludeList(); if (excludeList != null) { if (excludeList.contains(className)) { excluded = true; } else if (excludeList.contains(propertyName)) { excluded = true; } } // end if return excluded; }
public Integer[] areas() { /* Return a list of all areanumbers */ ArrayList<Integer> list = new ArrayList<Integer>(); for (int f : area) { if (!(list.contains(f))) { // Add all areanumbers that not already in list list.add(f); } } Integer[] i = new Integer[list.size()]; // Convert the list to array return list.toArray(i); // and return the array }
/** * Gets the list of the vnmrj users(operators) for the current unix user logged in * * @return the list of vnmrj users */ protected Object[] getOperators() { String strUser = System.getProperty("user.name"); User user = LoginService.getDefault().getUser(strUser); ArrayList<String> aListOperators = user.getOperators(); if (aListOperators == null || aListOperators.isEmpty()) aListOperators = new ArrayList<String>(); Collections.sort(aListOperators); if (aListOperators.contains(strUser)) aListOperators.remove(strUser); aListOperators.add(0, strUser); return (aListOperators.toArray()); }
public void onInvite( String targetNick, String sender, String sourceLogin, String sourceHostname, String channel) { if (!ignored.contains(channel)) { try { this.appendChannel(channel, sender); } catch (IOException ex) { this.sendError(sender, ex.toString()); } } else { ignoredChannel(sender, channel); } }
public static void procedure(int[] amts) { if (visited[amts[0]][amts[1]]) // System.out.println(amts[0] + " " + amts[1] + " " + amts[2] + " " + "returned"); return; // System.out.println(amts[0] + " " + amts[1] + " " + amts[2] + " " + "visited"); visited[amts[0]][amts[1]] = true; // if the first bucket is empty, record the amount of milk in the third bucket if (amts[0] == 0 && !finalValues.contains(amts[2])) finalValues.add(amts[2]); for (int a = 0; a < 3; a++) for (int b = 0; b < 3; b++) if (b != a && amts[a] > 0 && amts[b] < caps[b]) procedure(pour(amts, a, b)); }
List keepUniqueTerms(List hypernymsList) { ArrayList uniqueList = new ArrayList(); ArrayList uniqueHypernymList = new ArrayList(); for (int i = 0; i < hypernymsList.size(); i++) { IWord word = (IWord) hypernymsList.get(i); if (!uniqueList.contains(word.getLemma().toString())) { uniqueList.add(word.getLemma().toString()); uniqueHypernymList.add(word); } } return uniqueHypernymList; }
public static void main(String[] args) { Scanner scanner = null; // scanner for input file if (args.length == 1) { try { scanner = new Scanner(new File(args[0])); startTime = System.nanoTime(); while (scanner.hasNext()) { String currWord = scanner.next(); String sortedWord = alphaLowerSort(currWord); ArrayList<String> listAtKey = anagrams.get(sortedWord); if (listAtKey == null) { listAtKey = new ArrayList<String>(); anagrams.put(sortedWord, listAtKey); listAtKey.add(currWord); } else { if (!listAtKey.contains(currWord.toLowerCase())) listAtKey.add(currWord.toLowerCase()); } } endTime = System.nanoTime(); String mostAnagramsKey = null; int mostAnagramsSize = 0; for (Entry<String, ArrayList<String>> entry : anagrams.entrySet()) { System.out.println("Anagram(s) at key \"" + entry.getKey() + "\" : " + entry.getValue()); int numAnagrams = entry.getValue().size(); if (mostAnagramsKey == null) { mostAnagramsKey = entry.getKey(); mostAnagramsSize = entry.getValue().size(); } else if (numAnagrams > anagrams.get(mostAnagramsKey).size()) { mostAnagramsKey = entry.getKey(); mostAnagramsSize = entry.getValue().size(); } } System.out.println("\n-- Runtime Statistics --"); System.out.println("Number of anagram sets: " + anagrams.size()); System.out.println("Algorithm Runtime: " + (endTime - startTime) / 1000000000.0 + "s"); System.out.println("Largest set of anagrams: " + anagrams.get(mostAnagramsKey)); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } else { System.err.println("Error: Invalid number of args"); System.exit(0); } } // end main()
static String[] getFontList() { init(); ArrayList fontNames = new ArrayList(); Iterator fonts = fontNameMap.keySet().iterator(); int dotidx; while (fonts.hasNext()) { String fontname = (String) fonts.next(); if ((dotidx = fontname.indexOf('.')) == -1) dotidx = fontname.length(); fontname = fontname.substring(0, dotidx); if (!fontNames.contains(fontname)) fontNames.add(fontname); } return (String[]) fontNames.toArray(new String[fontNames.size()]); }
/** * Use exponential runtime tagging algorithm (evaluates trained Markov model). NOTE: do not use * this algorithm for long input word sequences - instead, break up long sequences of text into * smaller pieces (i.e., process just a few sentences at a time). */ public List<String> exponential_tagging_algorithm(List<String> words) { possibleTags = new ArrayList<ArrayList<String>>(); int num = words.size(); indices = new int[num]; counts = new int[num]; int[] best_indices = new int[num]; for (int i = 0; i < num; i++) { indices[i] = 0; counts[i] = 0; } for (int i = 0; i < num; i++) { String word = "" + words.get(i); List<String> v = lexicon.get(word); ArrayList<String> v2 = new ArrayList<String>(); // possible tags at index i for (int j = 0; j < v.size(); j++) { String tag = "" + v.get(j); if (v2.contains(tag) == false) { v2.add(tag); counts[i]++; } } possibleTags.add(v2); // possible tags at index i System.out.print("^^ word: " + word + ", tag count: " + counts[i] + ", tags: "); for (int j = 0; j < v2.size(); j++) System.out.print(" " + v2.get(j)); System.out.println(); } float best_score = -9999; do { System.out.print("Current indices:"); for (int k = 0; k < num; k++) System.out.print(" " + indices[k]); System.out.println(); float score = score(words); if (score > best_score) { best_score = score; System.out.println(" ** ** new best score: " + best_score); for (int m = 0; m < num; m++) best_indices[m] = indices[m]; } } while (incrementIndices(num)); List<String> tags = new ArrayList<String>(num); for (int i = 0; i < num; i++) { List<String> v = possibleTags.get(i); tags.add(v.get(best_indices[i])); } return tags; }
@Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Hashtable<String, Integer> wordCounts = new Hashtable<String, Integer>(); ArrayList docName = new ArrayList<String>(); LinkedList wordName = new LinkedList<String>(); while (values.iterator().hasNext()) { String[] items = values.iterator().next().toString().split("@"); if (!wordName.contains(items[0])) { wordName.add(items[0]); } String[] keys = items[1].split(":|,"); for (int i = 0; i < keys.length; i += 2) { if (!docName.contains(keys[i])) { docName.add(keys[i]); wordCounts.put(keys[i], 0); } int tmp = wordCounts.get(keys[i]); tmp += Integer.parseInt(keys[i + 1]); wordCounts.put(keys[i], tmp); } } for (int i = 0; i < docName.size() - 1; ++i) { for (int j = i + 1; j < docName.size(); ++j) { if (wordCounts.get(docName.get(i)) < wordCounts.get(docName.get(j))) { String stmp = docName.get(i).toString(); docName.set(i, docName.get(j).toString()); docName.set(j, stmp); } } } String retKey = wordName.get(0).toString(); for (int i = 1; i < wordName.size(); ++i) { retKey += "," + wordName.get(i); } String retValue = ""; // ="\n" + docName.get(0).toString() + ":" + // wordCounts.get(docName.get(0).toString()); for (int i = 0; i < docName.size(); ++i) { retValue += "\n" + docName.get(i).toString() + ": " + wordCounts.get(docName.get(i).toString()); } context.write(new Text(retKey), new Text(retValue)); }