Java Code Examples for java.util.TreeMap#values()

The following examples show how to use java.util.TreeMap#values() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Create a list of services ordered according to the ordering given in the
 * service descriptor files. Note, that the descriptor will be looked up
 * in the whole classpath space, which can result in reading in multiple
 * descriptors with a single path. Note, that the reading order for multiple
 * resources with the same name is not defined.
 *
 * @param descriptorPaths a list of resource paths which are handle in the given order.
 *        Normally, default service should be given as first parameter so that custom
 *        descriptors have a chance to remove a default service.
 * @param <T> type of the service objects to create
 * @return a ordered list of created services or an empty list.
 */
public <T> List<T> createServiceObjects(String... descriptorPaths) {
    try {
        ServiceEntry.initDefaultOrder();
        TreeMap<ServiceEntry,T> serviceMap = new TreeMap<ServiceEntry,T>();
        for (String descriptor : descriptorPaths) {
            readServiceDefinitions(serviceMap, descriptor);
        }
        ArrayList<T> ret = new ArrayList<T>();
        for (T service : serviceMap.values()) {
            ret.add(service);
        }
        return ret;
    } finally {
        ServiceEntry.removeDefaultOrder();
    }
}
 
Example 2
public String toString(){
	StringBuilder b = new StringBuilder();
	for(K reference: keySet()){
		b.append("\nReference -"+reference);
		TreeMap<V, LinkedList<V>> innerMap = get(reference);
		for(List<V> list : innerMap.values()){
			b.append(System.lineSeparator());
			for(V entry:list){
				if(lineSeparatorInToString){
					if(entry!=null){
						b.append( entry  );						
					}
					b.append(System.lineSeparator());
				}else{
					b.append("[" + entry + "], " );					
				}
			}
		}
	}
	return b.toString();
}
 
Example 3
Source Project: Smack   File: SignalOmemoStoreConnector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<SignedPreKeyRecord> loadSignedPreKeys() {

    TreeMap<Integer, SignedPreKeyRecord> signedPreKeyRecordHashMap;
    try {
        signedPreKeyRecordHashMap = omemoStore.loadOmemoSignedPreKeys(getOurDevice());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return new ArrayList<>(signedPreKeyRecordHashMap.values());
}
 
Example 4
Source Project: j2objc   File: TreeMapTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * values collection contains all values
 */
public void testValues() {
    TreeMap map = map5();
    Collection s = map.values();
    assertEquals(5, s.size());
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 5
Source Project: jkube   File: EnvUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Extract from given properties a list of string values. The prefix is used to determine the subset of the
 * given properties from which the list should be extracted, the rest is used as a numeric index. If the rest
 * is not numeric, the order is not determined (all those props are appended to the end of the list)
 *
 * <p> NOTE: If suffix/index is "._combine" ({@link #PROPERTY_COMBINE_POLICY_SUFFIX}) it is ignored!
 * This is reserved for combine policy tweaking.
 *
 * @param prefix     for selecting the properties from which the list should be extracted
 * @param properties properties from which to extract from
 * @return parsed list or null if no element with prefixes exists
 */
public static List<String> extractFromPropertiesAsList(String prefix, Properties properties) {
    TreeMap<Integer, String> orderedMap = new TreeMap<>();
    List<String> rest = new ArrayList<>();
    Enumeration names = properties.propertyNames();
    String prefixP = prefix + ".";
    while (names.hasMoreElements()) {
        String key = (String) names.nextElement();
        if (propMatchesPrefix(prefixP, key)) {
            String index = key.substring(prefixP.length());

            if (PROPERTY_COMBINE_POLICY_SUFFIX.equals(index)) {
                continue;
            }

            String value = properties.getProperty(key);
            try {
                Integer nrIndex = Integer.parseInt(index);
                orderedMap.put(nrIndex, value);
            } catch (NumberFormatException exp) {
                rest.add(value);
            }
        }
    }
    List<String> ret = new ArrayList<>(orderedMap.values());
    ret.addAll(rest);
    return ret.size() > 0 ? ret : null;
}
 
Example 6
/**
 * Returns <code>true</code> if there is a repartition in progress. Otherwise returns <code>false</code>.
 *
 * @param storageNumber the storage number to check.
 * @return <code>true</code> if there is a repartition in progress. Otherwise returns <code>false</code>.
 */
private boolean isRepartitionInProgress(final byte storageNumber) {

   final TreeMap<ClusterNodeAddress, BucketOwner> storageBucketOwners = bucketOwners[storageNumber];
   for (final BucketOwner owner : storageBucketOwners.values()) {

      if (owner.hasInboundBuckets() || owner.hasInboundReplicas() || owner.hasOutboundBuckets() || owner.hasOutboundReplicas()) {

         return true;
      }
   }

   return false;
}
 
Example 7
public DoubleArrayTrieStringIntMap(TreeMap<String, Integer> map) {
    ArrayList<String> keys = new ArrayList<>(map.keySet());
    int[] values = new int[map.size()];
    Collection<Integer> values1 = map.values();
    int c = 0;
    for(Integer integer : values1){
        values[c++] = integer.intValue();
    }

    this.dat = new DoubleArrayTrie(keys);
    this.values = values;
}
 
Example 8
private List<TaskState> sortTasksById(JobState jobState) {
    TreeMap<TaskId, TaskState> sortedTasks = new TreeMap<>(new Comparator<TaskId>() {
        @Override
        public int compare(TaskId o1, TaskId o2) {
            return Integer.parseInt(o1.value()) - Integer.parseInt(o2.value());
        }
    });
    sortedTasks.putAll(jobState.getHMTasks());
    return new ArrayList<>(sortedTasks.values());
}
 
Example 9
Source Project: siddhi   File: CacheTableLFU.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteEntriesUsingCachePolicy(int numRowsToDelete) {
    IndexEventHolder indexEventHolder = (IndexEventHolder) stateHolder.getState().getEventHolder();
    if (numRowsToDelete >= indexEventHolder.size()) {
        indexEventHolder.deleteAll();
    } else {
        Set<Object> keys = indexEventHolder.getAllPrimaryKeyValues();
        TreeMap<Integer, Object> toDelete = new TreeMap<>();
        for (Object key : keys) {
            if (toDelete.size() < numRowsToDelete) {
                toDelete.put((Integer) indexEventHolder.getEvent(key).getOutputData()[cachePolicyAttributePosition],
                        key);
            } else {
                Integer count = (Integer) indexEventHolder.getEvent(key).
                        getOutputData()[cachePolicyAttributePosition];
                Integer firstKey = toDelete.firstKey();
                if (count < firstKey) {
                    toDelete.remove(firstKey);
                    toDelete.put(count, key);
                }
            }
        }
        for (Object deleteKey : toDelete.values()) {
            if (deleteKey != null) {
                indexEventHolder.deleteEvent(deleteKey);
            }
        }
    }
}
 
Example 10
Source Project: hbase   File: BackupManifest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the image list of this backup for restore in time order.
 * @param reverse If true, then output in reverse order, otherwise in time order from old to new
 * @return the backup image list for restore in time order
 */
public ArrayList<BackupImage> getRestoreDependentList(boolean reverse) {
  TreeMap<Long, BackupImage> restoreImages = new TreeMap<>();
  restoreImages.put(backupImage.startTs, backupImage);
  for (BackupImage image : backupImage.getAncestors()) {
    restoreImages.put(Long.valueOf(image.startTs), image);
  }
  return new ArrayList<>(reverse ? (restoreImages.descendingMap().values())
      : (restoreImages.values()));
}
 
Example 11
Source Project: ambry   File: NonBlockingRouterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensure that Stitch requests for given blob id reaches to all the mock servees in the {@link MockServerLayout}.
 * @param blobId The blob id of which stitch request will be created.
 * @param serverLayout The mock server layout.
 * @param chunksToStitch The list of {@link ChunkInfo} to stitch.
 * @param singleBlobSize The size of each chunk
 * @throws IOException
 */
private void ensureStitchInAllServers(String blobId, MockServerLayout serverLayout, List<ChunkInfo> chunksToStitch,
    int singleBlobSize) throws IOException {
  TreeMap<Integer, Pair<StoreKey, Long>> indexToChunkIdsAndChunkSizes = new TreeMap<>();
  int i = 0;
  for (ChunkInfo chunkInfo : chunksToStitch) {
    indexToChunkIdsAndChunkSizes.put(i,
        new Pair<>(new BlobId(chunkInfo.getBlobId(), mockClusterMap), chunkInfo.getChunkSizeInBytes()));
    i++;
  }
  ByteBuffer serializedContent;
  int totalSize = singleBlobSize * chunksToStitch.size();
  if (routerConfig.routerMetadataContentVersion == MessageFormatRecord.Metadata_Content_Version_V2) {
    serializedContent = MetadataContentSerDe.serializeMetadataContentV2(singleBlobSize, totalSize,
        indexToChunkIdsAndChunkSizes.values().stream().map(Pair::getFirst).collect(Collectors.toList()));
  } else {
    List<Pair<StoreKey, Long>> orderedChunkIdList = new ArrayList<>(indexToChunkIdsAndChunkSizes.values());
    serializedContent = MetadataContentSerDe.serializeMetadataContentV3(totalSize, orderedChunkIdList);
  }
  BlobId id = new BlobId(blobId, mockClusterMap);
  for (MockServer server : serverLayout.getMockServers()) {
    if (!server.getBlobs().containsKey(blobId)) {
      server.send(
          new PutRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, id,
              putBlobProperties, ByteBuffer.wrap(putUserMetadata), Unpooled.wrappedBuffer(serializedContent),
              serializedContent.remaining(), BlobType.MetadataBlob, null)).release();
    }
  }
}
 
Example 12
Source Project: buck   File: DependenciesOptimizer.java    License: Apache License 2.0 5 votes vote down vote up
private void uniqueSort(BuckExpressionListOrComprehension expressionListOrComprehension) {
  List<BuckExpression> expressionList = expressionListOrComprehension.getExpressionList();
  if (expressionList.isEmpty()) {
    return; // nothing to sort
  }
  TreeMap<String, PsiElement> treeMap =
      new TreeMap<>(DependenciesOptimizer::compareDependencyStrings);
  boolean isSorted = true;
  for (int i = 0; i < expressionList.size(); i++) {
    if (isSorted
        && i > 0
        && compareDependencyStrings(
                expressionList.get(i - 1).getText(), expressionList.get(i).getText())
            > 0) {
      isSorted = false;
      sortedArrays++;
    }
    treeMap.put(expressionList.get(i).getText(), expressionList.get(i).copy());
  }
  if (treeMap.size() < expressionList.size()) {
    prunedDependencies += expressionList.size() - treeMap.size();
  }
  int index = 0;
  for (PsiElement psiElement : treeMap.values()) {
    expressionList.get(index).replace(psiElement);
    index++;
  }
  if (index < expressionList.size() && index > 0) {
    expressionListOrComprehension.deleteChildRange(
        expressionList.get(index).getPrevSibling(),
        expressionListOrComprehension.getLastChild());
  }
}
 
Example 13
Source Project: calcite-avatica   File: JdbcResultSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts an Array into a List using {@link Array#getResultSet()}. This implementation is
 * recursive and can parse multi-dimensional arrays.
 */
static List<?> extractUsingResultSet(Array array, Calendar calendar) throws SQLException {
  ResultSet arrayValues = array.getResultSet();
  TreeMap<Integer, Object> map = new TreeMap<>();
  while (arrayValues.next()) {
    // column 1 is the index in the array, column 2 is the value.
    // Recurse on `getValue` to unwrap nested types correctly.
    // `j` is zero-indexed and incremented for us, thus we have `1` being used twice.
    map.put(arrayValues.getInt(1), getValue(arrayValues, array.getBaseType(), 1, calendar));
  }
  // If the result set is not in the same order as the actual Array, TreeMap fixes that.
  // Need to make a concrete list to ensure Jackson serialization.
  return new ArrayList<>(map.values());
}
 
Example 14
Source Project: lucene-solr   File: SplitOp.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *   Returns a list of range counts sorted by the range lower bound, using the indexed "id" field (i.e. the terms are full IDs, not just prefixes)
 */
static Collection<RangeCount> getHashHistogramFromId(SolrIndexSearcher searcher, String idField, DocRouter router, DocCollection collection) throws IOException {
  RTimer timer = new RTimer();

  TreeMap<DocRouter.Range, RangeCount> counts = new TreeMap<>();

  Terms terms = MultiTerms.getTerms(searcher.getIndexReader(), idField);
  if (terms == null) {
    return counts.values();
  }

  int numPrefixes = 0;
  int numCollisions = 0;
  long sumBuckets = 0;


  byte sep = (byte) CompositeIdRouter.SEPARATOR.charAt(0);
  TermsEnum termsEnum = terms.iterator();
  BytesRef currPrefix = new BytesRef();  // prefix of the previous "id" term
  int bucketCount = 0; // count of the number of docs in the current bucket

  // We're going to iterate over all terms, so do the minimum amount of work per term.
  // Terms are sorted, so all terms sharing a prefix will be grouped together.  The extra work
  // is really just limited to stepping over all the terms in the id field.
  for (;;) {
    BytesRef term = termsEnum.next();

    // compare to current prefix bucket and see if this new term shares the same prefix
    if (term != null && term.length >= currPrefix.length && currPrefix.length > 0) {
      if (StringHelper.startsWith(term, currPrefix)) {
        bucketCount++;  // use 1 since we are dealing with unique ids
        continue;
      }
    }

    // At this point the prefix did not match, so if we had a bucket we were working on, record it.
    if (currPrefix.length > 0) {
      numPrefixes++;
      sumBuckets += bucketCount;
      String currPrefixStr = currPrefix.utf8ToString();
      DocRouter.Range range = router.getSearchRangeSingle(currPrefixStr, null, collection);

      RangeCount rangeCount = new RangeCount(range, bucketCount);
      bucketCount = 0;

      RangeCount prev = counts.put(rangeCount.range, rangeCount);
      if (prev != null) {
        // we hit a hash collision, so add the buckets together.
        rangeCount.count += prev.count;
        numCollisions++;
      }
    }

    // if the current term is null, we ran out of values
    if (term == null) break;

    // find the new prefix (if any)

    // resize if needed
    if (currPrefix.length < term.length) {
      currPrefix.bytes = new byte[term.length+10];
    }

    // Copy the bytes up to and including the separator, and set the length if the separator is found.
    // If there was no separator, then length remains 0 and it's the indicator that we have no prefix bucket
    currPrefix.length = 0;
    for (int i=0; i<term.length; i++) {
      byte b = term.bytes[i + term.offset];
      currPrefix.bytes[i] = b;
      if (b == sep) {
        currPrefix.length = i + 1;
        bucketCount++;
        break;
      }
    }
  }

  if (log.isInfoEnabled()) {
    log.info("Split histogram from idField {}: ms={}, numBuckets={} sumBuckets={} numPrefixes={} numCollisions={}"
        , idField, timer.getTime(), counts.size(), sumBuckets, numPrefixes, numCollisions);
  }

  return counts.values();
}
 
Example 15
Source Project: TrakEM2   File: Bucket.java    License: GNU General Public License v3.0 4 votes vote down vote up
/** Find All Displayable objects that intersect with the given srcRect and return them ordered by stack_index. Of @param visible_only is true, then hidden Displayable objects are ignored.
 *
 * Fast and dirty, never returns a false negative but may return a false positive. */
synchronized final Collection<Displayable> roughlyFind(final Rectangle srcRect, final Layer layer, final boolean visible_only) {
	final TreeMap<Integer,Displayable> accum = new TreeMap<Integer,Displayable>();
	roughlyFind(accum, srcRect, layer, visible_only);
	return accum.values(); // sorted by integer key
}
 
Example 16
/**
 * A parser for the symop.lib file provided by CCP4. Note: this file is not getting re-distributed by BioJava.
 * It can be downloaded from:
 *
 *  http://www.ccp4.ac.uk/cvs/viewvc.cgi/libccp4/data/symop.lib?revision=1.10&view=markup
 *
 * Note: this file is not needed by BioJava. BioJava loads equivalent information from the file spacegroups.xml
 *
 * @param symoplibIS
 * @return
 */
public static TreeMap<Integer,SpaceGroup> parseSymopLib(InputStream symoplibIS) {
	TreeMap<Integer, SpaceGroup> map = new TreeMap<Integer, SpaceGroup>();
	name2sgs = new HashMap<String, SpaceGroup>();
	try {
		BufferedReader br = new BufferedReader(new InputStreamReader(symoplibIS));
		String line;
		SpaceGroup currentSG = null;
		while ((line=br.readLine())!=null) {
			if (!line.startsWith(" ")) {
				if (currentSG!=null) {
					map.put(currentSG.getId(),currentSG);
					name2sgs.put(currentSG.getShortSymbol(), currentSG);
					if (currentSG.getAltShortSymbol()!=null) {
						// we add also alternative name to map so we can look it up
						name2sgs.put(currentSG.getAltShortSymbol(), currentSG);
					}
				}

				int idxFirstSpace = line.indexOf(' ');
				int idxSecondSpace = line.indexOf(' ',idxFirstSpace+1);
				int idxThirdSpace = line.indexOf(' ',idxSecondSpace+1);
				int id = Integer.parseInt(line.substring(0, idxFirstSpace));
				int multiplicity = Integer.parseInt(line.substring(idxFirstSpace+1, idxSecondSpace));
				int primitiveMultiplicity = Integer.parseInt(line.substring(idxSecondSpace+1, idxThirdSpace));
				Matcher m = namePat.matcher(line);
				String shortSymbol = null;
				String altShortSymbol = null;
				String brav = null;
				if (m.matches()) {
					brav = m.group(1);
					altShortSymbol = m.group(2); // null if there is no match
					if (altShortSymbol!=null) altShortSymbol = altShortSymbol.trim().replaceAll("'", "");
					shortSymbol = m.group(3);
				}
				currentSG = new SpaceGroup(id, multiplicity, primitiveMultiplicity, shortSymbol, altShortSymbol, BravaisLattice.getByName(brav));
			} else {
				currentSG.addTransformation(line.trim());
			}
		}
		br.close();
		// and we add the last SG
		map.put(currentSG.getId(), currentSG);
		name2sgs.put(currentSG.getShortSymbol(), currentSG);
		if (currentSG.getAltShortSymbol()!=null) {
			// we add also alternative name to map so we can look it up
			name2sgs.put(currentSG.getAltShortSymbol(), currentSG);
		}

	} catch (IOException e) {
		logger.error("Fatal error! Can't read symop.lib file. Error: "+e.getMessage()+". ");
		System.exit(1);
	}

	for (SpaceGroup sg:map.values()) {
		sg.initializeCellTranslations();
	}
	return map;
}
 
Example 17
Source Project: TrakEM2   File: Bucket.java    License: GNU General Public License v3.0 4 votes vote down vote up
/** Find all Displayable objects that intersect the given Area and return them ordered by stack_index. If @param visible_only is trye, then hidden Displayable objects are ignored. */
synchronized final Collection<Displayable> find(final Class<?> c, final Area area, final Layer layer, final boolean visible_only, final boolean instance_of) {
	final TreeMap<Integer,Displayable> accum = new TreeMap<Integer,Displayable>();
	find(accum, c, area, layer, visible_only, instance_of);
	return accum.values(); // sorted by integer key
}
 
Example 18
Source Project: TrakEM2   File: Patch.java    License: GNU General Public License v3.0 4 votes vote down vote up
public ArrayList<Patch> getStackPatches() {
	final TreeMap<Double,Patch> ht = new TreeMap<Double,Patch>();
	getStackPatchesNR(ht);
	return new ArrayList<Patch>(ht.values()); // sorted by z
}
 
Example 19
Source Project: chipster   File: CoverageTrack.java    License: MIT License 4 votes vote down vote up
private Collection<Drawable> getCoverageDrawables(Strand strand, Color color) {				
	
	Collection<Drawable> drawables = getEmptyDrawCollection();

	Chromosome chr = getView().getBpRegion().start.chr;
	
	// If SNP highlight mode is on, we need reference sequence data
	char[] refSeq = ReadPileTrack.getReferenceArray(refReads, view, Strand.FORWARD);

	// Count width of a single bp in pixels
	float bpWidth = (float) (getView().getWidth() / getView().getBpRegionDouble().getLength());

	// Count maximum y coordinate (the bottom of the track)
	int bottomlineY = 0;

	int previousValueY = 0;
	int previousEndX = -1;
	
	//Line color is opaque
	Color lineColor = new Color(color.getRGB(), false);
			
	TreeMap<BpCoord, Base> totalBases = coverageStorage.getTotalBases();
	
	for (Base base : totalBases.values()) {
		
		Nucleotide reference = null;
		int viewIndex = (int) (base.getBpLocation() - view.getBpRegion().start.bp);
		if (viewIndex >= 0 && viewIndex < refSeq.length) {
			reference = Nucleotide.fromCharacter(refSeq[viewIndex]);
			Base refBase = new Base(base.getBpLocation(), reference);
			refBase.setNucleotideCounts(base.getNucleotideCounts());
			base = refBase;
		}
					
		BpCoord location = new BpCoord(base.getBpLocation(), chr);
		float startX = getView().bpToTrackFloat(location);
		//Round together with position dividends to get the same result than where next block will start
		int width = (int)(startX + bpWidth) - (int)startX;
		
		int profileY = 0;
		
		Base coverageBase = coverageStorage.getBase(location, strand);			
		
		if (coverageBase != null) {
			profileY = super.getScaledY(coverageBase.getCoverage());
		} else {
			//this totalBase is on the wrong strand
			continue;
		}
		
		int valueY = (int)(bottomlineY + profileY);
		
		drawables.add(new RectDrawable((int)startX, bottomlineY, width,  valueY, color, null));
		
		//Check if there was a gap between profile blocks
		if (previousEndX < (int)startX) {
			
			//End last block with line
			drawables.add(new LineDrawable(previousEndX, bottomlineY, previousEndX,  previousValueY, lineColor));
			
			//Start next line from the bottom
			previousValueY = 0;
		}
		
		//Draw line between height difference of previous and current block
		drawables.add(new LineDrawable((int)startX, previousValueY, (int)startX,  valueY, lineColor));
		//Draw line on top of the current block
		drawables.add(new LineDrawable((int)startX, valueY, (int)startX + width,  valueY, lineColor));									
		
		drawSNPBar(drawables, (int)bpWidth, bottomlineY, base, strand, (int)startX);
		
		previousValueY = valueY;
		previousEndX = (int)startX + width;
	}		
	
	//End last block with line
	drawables.add(new LineDrawable(previousEndX, bottomlineY, previousEndX,  previousValueY, lineColor));

	return drawables;
}
 
Example 20
@RequestMapping("/swapOption")
   public String swapOption(HttpServletRequest request) {

Integer questionNumber = WebUtil.readIntParam(request, "questionNumber", true);

// Work out which two to swap and make swap1 the smaller of the two.
// They should always be consecutive, so we can (the new) swap1 with whichever is the next item.
int swap1 = WebUtil.readIntParam(request, "optionNumber1");
int swap2 = WebUtil.readIntParam(request, "optionNumber2");
if (swap2 < swap1) {
    swap1 = swap2;
}

boolean useAssessmentVersion = WebUtil.readBooleanParam(request, "assess", false);
String containingDivName = WebUtil.readStrParam(request, "containingDivName", true);
String prefixParam = containingDivName != null ? containingDivName + "assmcq" : "question";
TreeMap<Integer, Option> optionsMap = getOptions(request, questionNumber, prefixParam);
// reorder the options and setup the return value
LinkedList<Option> options = new LinkedList<>();

Option swap = null;
for (Option option : optionsMap.values()) {
    if (swap != null) {
	swap.setDisplayOrder(option.getDisplayOrder());
	option.setDisplayOrder(swap1);
	options.add(option);
	options.add(swap);
	swap = null;
    } else if (option.getDisplayOrder() == swap1) {
	swap = option;
    } else {
	options.add(option);
    }
}
if (swap != null) {
    // something wrong - ended up with swap object last!
    options.add(swap);
}
request.setAttribute("questionNumber", questionNumber);
request.setAttribute("options", options);
request.setAttribute("optionCount", options.size());
request.setAttribute("containingDivName", WebUtil.readStrParam(request, "containingDivName", true));
return (useAssessmentVersion ? "authoring/template/tool/assessredooption"
	: "authoring/template/tool/mcredooption");
   }