Java Code Examples for java.util.TreeSet#toArray()

The following examples show how to use java.util.TreeSet#toArray() . 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
Source File: NumberFormatDialog.java    From tracker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets an array of unit dimensions for all currently selected variables.
 *
 * @return array of unit dimensions
 */
private String[] getCurrentDimensions() {
  TTrack track = TTrack.getTrack(trackID);
  if (track==null) return new String[0];
  Class<? extends TTrack> trackType = getTrackType(track);
	TreeSet<String> dimensions = new TreeSet<String>(); 
int[] indices = variableList.getSelectedIndices();
Object[] selected = new Object[indices.length];
for (int j=0; j<indices.length; j++) {
	selected[j] = displayedNames[indices[j]];
}
for (Object displayedName : selected) {
	String name = realNames.get(displayedName.toString());
		String dim = getVariableDimensions(trackType, name);
		if (dim!=null) {
			dimensions.add(dim);
		}
}
return dimensions.toArray(new String[dimensions.size()]);
}
 
Example 2
Source File: CorrectionSettingsFragment.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
private void overwriteUserDictionaryPreference(final Preference userDictionaryPreference) {
    final Activity activity = getActivity();
    final TreeSet<String> localeList = UserDictionaryList.getUserDictionaryLocalesSet(activity);
    if (null == localeList) {
        // The locale list is null if and only if the user dictionary service is
        // not present or disabled. In this case we need to remove the preference.
        getPreferenceScreen().removePreference(userDictionaryPreference);
    } else if (localeList.size() <= 1) {
        userDictionaryPreference.setFragment(UserDictionarySettings.class.getName());
        // If the size of localeList is 0, we don't set the locale parameter in the
        // extras. This will be interpreted by the UserDictionarySettings class as
        // meaning "the current locale".
        // Note that with the current code for UserDictionaryList#getUserDictionaryLocalesSet()
        // the locale list always has at least one element, since it always includes the current
        // locale explicitly. @see UserDictionaryList.getUserDictionaryLocalesSet().
        if (localeList.size() == 1) {
            final String locale = (String)localeList.toArray()[0];
            userDictionaryPreference.getExtras().putString("locale", locale);
        }
    } else {
        userDictionaryPreference.setFragment(UserDictionaryList.class.getName());
    }
}
 
Example 3
Source File: MmsParameterSet.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public String[] getEditableDimensionArray() {
    TreeSet dim_set = new TreeSet();

    for (Iterator i = parameters.values().iterator(); i.hasNext();) {
        Parameter p = (Parameter)(i.next());
        if (p.getSize() > 0) {
            String foo = "";
            for (int j = 0; j < p.getNumDim(); j++) {
                if (j != 0) foo = foo + ",";
                foo = foo + p.getDimension(j).getName();
            }
            dim_set.add(foo);
        }
    }
    Object[] objs = dim_set.toArray();
    String[] ret = new String[objs.length];
    for (int i = 0; i < objs.length; i++) {
        ret[i] = (String)objs[i];
    }
    return ret;
}
 
Example 4
Source File: RecursiveMassDetector.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
public DataPoint[] getMassValues(DataPoint dataPoints[], ParameterSet parameters) {

    double noiseLevel =
        parameters.getParameter(RecursiveMassDetectorParameters.noiseLevel).getValue();
    double minimumMZPeakWidth =
        parameters.getParameter(RecursiveMassDetectorParameters.minimumMZPeakWidth).getValue();
    double maximumMZPeakWidth =
        parameters.getParameter(RecursiveMassDetectorParameters.maximumMZPeakWidth).getValue();

    TreeSet<DataPoint> mzPeaks =
        new TreeSet<DataPoint>(new DataPointSorter(SortingProperty.MZ, SortingDirection.Ascending));

    // Find MzPeaks
    recursiveThreshold(mzPeaks, dataPoints, 1, dataPoints.length - 1, noiseLevel,
        minimumMZPeakWidth, maximumMZPeakWidth, 0);
    return mzPeaks.toArray(new DataPoint[0]);
  }
 
Example 5
Source File: DefineLst.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String[] unparse(LoadContext context, CDOMObject obj)
{
	Set<VariableKey> keys = context.getObjectContext().getVariableKeys(obj);
	TreeSet<String> set = new TreeSet<>();
	if (keys != null && !keys.isEmpty())
	{
		for (VariableKey key : keys)
		{
			set.add(key.toString() + Constants.PIPE + context.getObjectContext().getVariable(obj, key));
		}
	}
	if (set.isEmpty())
	{
		return null;
	}
	return set.toArray(new String[0]);
}
 
Example 6
Source File: CorrectionSettingsFragment.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
private void overwriteUserDictionaryPreference(final Preference userDictionaryPreference) {
    final Activity activity = getActivity();
    final TreeSet<String> localeList = UserDictionaryList.getUserDictionaryLocalesSet(activity);
    if (null == localeList) {
        // The locale list is null if and only if the user dictionary service is
        // not present or disabled. In this case we need to remove the preference.
        getPreferenceScreen().removePreference(userDictionaryPreference);
    } else if (localeList.size() <= 1) {
        userDictionaryPreference.setFragment(UserDictionarySettings.class.getName());
        // If the size of localeList is 0, we don't set the locale parameter in the
        // extras. This will be interpreted by the UserDictionarySettings class as
        // meaning "the current locale".
        // Note that with the current code for UserDictionaryList#getUserDictionaryLocalesSet()
        // the locale list always has at least one element, since it always includes the current
        // locale explicitly. @see UserDictionaryList.getUserDictionaryLocalesSet().
        if (localeList.size() == 1) {
            final String locale = (String)localeList.toArray()[0];
            userDictionaryPreference.getExtras().putString("locale", locale);
        }
    } else {
        userDictionaryPreference.setFragment(UserDictionaryList.class.getName());
    }
}
 
Example 7
Source File: ClassDefinition.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
private ClassDefinition(int code, Class<?> clazz, TreeSet<PropertyDefinition> properties, Specification specification) {
    this.code = code;
    this.clazz = clazz;
    this.name = clazz.getName();
    this.specification = specification;
    this.properties = properties.toArray(new PropertyDefinition[properties.size()]);
    // 不是所有类型都有无参数构造器
    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        if (constructor.getParameterTypes().length == 0) {
            ReflectionUtility.makeAccessible(constructor);
            this.constructor = constructor;
            break;
        }
    }
    // if (this.constructor == null && !this.clazz.isEnum()) {
    // String message = StringUtility.format("类型[{}]缺乏无参数构造器,不符合编解码规范",
    // clazz.getName());
    // throw new CodecException(message);
    // }
}
 
Example 8
Source File: CorrectionSettingsFragment.java    From Android-Keyboard with Apache License 2.0 6 votes vote down vote up
private void overwriteUserDictionaryPreference(final Preference userDictionaryPreference) {
    final Activity activity = getActivity();
    final TreeSet<String> localeList = UserDictionaryList.getUserDictionaryLocalesSet(activity);
    if (null == localeList) {
        // The locale list is null if and only if the user dictionary service is
        // not present or disabled. In this case we need to remove the preference.
        getPreferenceScreen().removePreference(userDictionaryPreference);
    } else if (localeList.size() <= 1) {
        userDictionaryPreference.setFragment(UserDictionarySettings.class.getName());
        // If the size of localeList is 0, we don't set the locale parameter in the
        // extras. This will be interpreted by the UserDictionarySettings class as
        // meaning "the current locale".
        // Note that with the current code for UserDictionaryList#getUserDictionaryLocalesSet()
        // the locale list always has at least one element, since it always includes the current
        // locale explicitly. @see UserDictionaryList.getUserDictionaryLocalesSet().
        if (localeList.size() == 1) {
            final String locale = (String)localeList.toArray()[0];
            userDictionaryPreference.getExtras().putString("locale", locale);
        }
    } else {
        userDictionaryPreference.setFragment(UserDictionaryList.class.getName());
    }
}
 
Example 9
Source File: FollowersLst.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String[] unparse(LoadContext context, CDOMObject obj)
{
	Changes<FollowerLimit> changes = context.getObjectContext().getListChanges(obj, ListKey.FOLLOWERS);
	if (changes == null || changes.isEmpty())
	{
		return null;
	}
	TreeSet<String> returnSet = new TreeSet<>();
	for (FollowerLimit fl : changes.getAdded())
	{
		String followerType = fl.getCompanionList().getLSTformat(false);
		Formula followerNumber = fl.getValue();
		returnSet.add(followerType + Constants.PIPE + followerNumber.toString());
	}
	return returnSet.toArray(new String[0]);
}
 
Example 10
Source File: MemstoreKeyValueScannerTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private ResultScanner generateResultScanner(KeyValue... kvs) {
    TreeSet<KeyValue> set = new TreeSet<>(KeyValue.COMPARATOR);

    set.addAll(Arrays.asList(kvs));

    KeyValue[] sortedKvs = new KeyValue[set.size()];
    set.toArray(sortedKvs);

    final Result result = Result.create(kvs);

    return new ResultScanner() {
        @Override
        public Result next() throws IOException {
            return result;
        }

        @Override
        public Result[] next(int nbRows) throws IOException {
            return new Result[] {result};
        }

        @Override
        public void close() {

        }

        public boolean renewLease() {
            return false;
        }

        public ScanMetrics getScanMetrics() {
            return null;
        }

        @Override
        public Iterator<Result> iterator() {
            return Arrays.asList(result).iterator();
        }
    };
}
 
Example 11
Source File: YMDBGateway.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
public String[] findCompounds(double mass, MZTolerance mzTolerance, int numOfResults,
    ParameterSet parameters) throws IOException {

  Range<Double> toleranceRange = mzTolerance.getToleranceRange(mass);

  String queryAddress = ymdbSearchAddress + "query_from=" + toleranceRange.lowerEndpoint()
      + "&query_to=" + toleranceRange.upperEndpoint();

  URL queryURL = new URL(queryAddress);

  // Submit the query
  logger.finest("Querying YMDB URL " + queryURL);
  String queryResult = InetUtils.retrieveData(queryURL);

  // Organize the IDs as a TreeSet to keep them sorted
  TreeSet<String> results = new TreeSet<String>();

  // Find IDs in the HTML data
  Pattern pat = Pattern.compile("/compounds/(YMDB[0-9]{5})");
  Matcher matcher = pat.matcher(queryResult);
  while (matcher.find()) {
    String ymdbID = matcher.group(1);
    results.add(ymdbID);
  }

  // Remove all except first numOfResults IDs. The reason why we first
  // retrieve all results and then remove those above numOfResults is to
  // keep the lowest YDMB IDs - these may be the most interesting ones.
  while (results.size() > numOfResults) {
    String lastItem = results.last();
    results.remove(lastItem);
  }

  return results.toArray(new String[0]);

}
 
Example 12
Source File: TreeSetTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * toArray contains all elements in sorted order
 */
public void testToArray() {
    TreeSet q = populatedSet(SIZE);
    Object[] o = q.toArray();
    for (int i = 0; i < o.length; i++)
        assertSame(o[i], q.pollFirst());
}
 
Example 13
Source File: JavaEEServerComboBoxModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private JavaEEServerComboBoxModel(J2eeModule.Type moduleType, Profile javaeeProfile) {
    String[] serverInstanceIDs = Deployment.getDefault().getServerInstanceIDs(Collections.singleton(moduleType), javaeeProfile);
    TreeSet<J2eePlatformModel> order = new TreeSet<>();
    for (String serverInstanceID : serverInstanceIDs) {
        try {
            order.add(new J2eePlatformModel(serverInstanceID));
        } catch (InstanceRemovedException ex) {
            //Shall not happen, however if it would we
            //Simply not add this item to the list
        }
    }
    platforms = order.toArray(new J2eePlatformModel[order.size()]);
}
 
Example 14
Source File: RestoreTablesClient.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Restore operation. Stage 2: resolved Backup Image dependency
 * @param backupManifestMap : tableName, Manifest
 * @param sTableArray The array of tables to be restored
 * @param tTableArray The array of mapping tables to restore to
 * @throws IOException exception
 */
private void restore(HashMap<TableName, BackupManifest> backupManifestMap,
    TableName[] sTableArray, TableName[] tTableArray, boolean isOverwrite) throws IOException {
  TreeSet<BackupImage> restoreImageSet = new TreeSet<>();

  for (int i = 0; i < sTableArray.length; i++) {
    TableName table = sTableArray[i];

    BackupManifest manifest = backupManifestMap.get(table);
    // Get the image list of this backup for restore in time order from old
    // to new.
    List<BackupImage> list = new ArrayList<>();
    list.add(manifest.getBackupImage());
    TreeSet<BackupImage> set = new TreeSet<>(list);
    List<BackupImage> depList = manifest.getDependentListByTable(table);
    set.addAll(depList);
    BackupImage[] arr = new BackupImage[set.size()];
    set.toArray(arr);
    restoreImages(arr, table, tTableArray[i], isOverwrite);
    restoreImageSet.addAll(list);
    if (restoreImageSet != null && !restoreImageSet.isEmpty()) {
      LOG.info("Restore includes the following image(s):");
      for (BackupImage image : restoreImageSet) {
        LOG.info("Backup: " + image.getBackupId() + " "
            + HBackupFileSystem.getTableBackupDir(image.getRootDir(), image.getBackupId(),
                table));
      }
    }
  }
  LOG.debug("restoreStage finished");
}
 
Example 15
Source File: XxlRpcLoadBalanceRoundStrategy.java    From xxl-rpc with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String route(String serviceKey, TreeSet<String> addressSet) {
    // arr
    String[] addressArr = addressSet.toArray(new String[addressSet.size()]);

    // round
    String finalAddress = addressArr[count(serviceKey)%addressArr.length];
    return finalAddress;
}
 
Example 16
Source File: ObjectUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the "best guess" middle value among comparables. If there is an even
 * number of total values, the lower of the two middle values will be returned.
 * @param <T> type of values processed by this method
 * @param items to compare
 * @return T at middle position
 * @throws NullPointerException if items is {@code null}
 * @throws IllegalArgumentException if items is empty or contains {@code null} values
 * @since 3.0.1
 */
public static <T extends Comparable<? super T>> T median(final T... items) {
    Validate.notEmpty(items);
    Validate.noNullElements(items);
    final TreeSet<T> sort = new TreeSet<T>();
    Collections.addAll(sort, items);
    @SuppressWarnings("unchecked") //we know all items added were T instances
    final
    T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    return result;
}
 
Example 17
Source File: SerialPortList.java    From PanamaHitek_Arduino with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get serial port names in Windows
 *
 * @since 2.3.0
 */
private static String[] getWindowsPortNames(Pattern pattern, Comparator<String> comparator) {
    String[] portNames = serialInterface.getSerialPortNames();
    if(portNames == null){
        return new String[]{};
    }
    TreeSet<String> ports = new TreeSet<String>(comparator);
    for(String portName : portNames){
        if(pattern.matcher(portName).find()){
            ports.add(portName);
        }
    }
    return ports.toArray(new String[ports.size()]);
}
 
Example 18
Source File: LoptOptimizeJoinRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Locates pairs of joins that are self-joins where the join can be removed
 * because the join condition between the two factors is an equality join on
 * unique keys.
 *
 * @param multiJoin join factors being optimized
 */
private void findRemovableSelfJoins(RelMetadataQuery mq, LoptMultiJoin multiJoin) {
  // Candidates for self-joins must be simple factors
  Map<Integer, RelOptTable> simpleFactors = getSimpleFactors(mq, multiJoin);

  // See if a simple factor is repeated and therefore potentially is
  // part of a self-join.  Restrict each factor to at most one
  // self-join.
  final List<RelOptTable> repeatedTables = new ArrayList<>();
  final TreeSet<Integer> sortedFactors = new TreeSet<>();
  sortedFactors.addAll(simpleFactors.keySet());
  final Map<Integer, Integer> selfJoinPairs = new HashMap<>();
  Integer [] factors =
      sortedFactors.toArray(new Integer[0]);
  for (int i = 0; i < factors.length; i++) {
    if (repeatedTables.contains(simpleFactors.get(factors[i]))) {
      continue;
    }
    for (int j = i + 1; j < factors.length; j++) {
      int leftFactor = factors[i];
      int rightFactor = factors[j];
      if (simpleFactors.get(leftFactor).getQualifiedName().equals(
          simpleFactors.get(rightFactor).getQualifiedName())) {
        selfJoinPairs.put(leftFactor, rightFactor);
        repeatedTables.add(simpleFactors.get(leftFactor));
        break;
      }
    }
  }

  // From the candidate self-join pairs, determine if there is
  // the appropriate join condition between the two factors that will
  // allow the join to be removed.
  for (Integer factor1 : selfJoinPairs.keySet()) {
    final int factor2 = selfJoinPairs.get(factor1);
    final List<RexNode> selfJoinFilters = new ArrayList<>();
    for (RexNode filter : multiJoin.getJoinFilters()) {
      ImmutableBitSet joinFactors =
          multiJoin.getFactorsRefByJoinFilter(filter);
      if ((joinFactors.cardinality() == 2)
          && joinFactors.get(factor1)
          && joinFactors.get(factor2)) {
        selfJoinFilters.add(filter);
      }
    }
    if ((selfJoinFilters.size() > 0)
        && isSelfJoinFilterUnique(
          mq,
          multiJoin,
          factor1,
          factor2,
          selfJoinFilters)) {
      multiJoin.addRemovableSelfJoinPair(factor1, factor2);
    }
  }
}
 
Example 19
Source File: ObjectUtils.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Find the "best guess" middle value among comparables. If there is an even
 * number of total values, the lower of the two middle values will be returned.
 * @param <T> type of values processed by this method
 * @param comparator to use for comparisons
 * @param items to compare
 * @return T at middle position
 * @throws NullPointerException if items or comparator is {@code null}
 * @throws IllegalArgumentException if items is empty or contains {@code null} values
 * @since 3.0.1
 */
public static <T> T median(Comparator<T> comparator, T... items) {
    Validate.notEmpty(items, "null/empty items");
    Validate.noNullElements(items);
    Validate.notNull(comparator, "null comparator");
    TreeSet<T> sort = new TreeSet<T>(comparator);
    Collections.addAll(sort, items);
    @SuppressWarnings("unchecked") //we know all items added were T instances
    T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    return result;
}
 
Example 20
Source File: ObjectUtils.java    From xposed-art with Apache License 2.0 3 votes vote down vote up
/**
 * Find the "best guess" middle value among comparables. If there is an even
 * number of total values, the lower of the two middle values will be returned.
 * @param <T> type of values processed by this method
 * @param items to compare
 * @return T at middle position
 * @throws NullPointerException if items is {@code null}
 * @throws IllegalArgumentException if items is empty or contains {@code null} values
 * @since 3.0.1
 */
public static <T extends Comparable<? super T>> T median(T... items) {
    Validate.notEmpty(items);
    Validate.noNullElements(items);
    TreeSet<T> sort = new TreeSet<T>();
    Collections.addAll(sort, items);
    @SuppressWarnings("unchecked") //we know all items added were T instances
    T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    return result;
}