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

The following examples show how to use java.util.TreeSet#add() . 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: MergingWindowSetTest.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Merge overlapping {@link TimeWindow}s.
 */
@Override
public void mergeWindows(TimeWindow newWindow, NavigableSet<TimeWindow> sortedWindows,
		MergeCallback<TimeWindow> callback) {
	TreeSet<TimeWindow> treeWindows = new TreeSet<>();
	treeWindows.add(newWindow);
	treeWindows.addAll(sortedWindows);

	TimeWindow earliestStart = treeWindows.first();

	List<TimeWindow> associatedWindows = new ArrayList<>();

	for (TimeWindow win : treeWindows) {
		if (win.getStart() < earliestStart.getEnd() && win.getStart() >= earliestStart.getStart()) {
			associatedWindows.add(win);
		}
	}

	TimeWindow target = new TimeWindow(earliestStart.getStart(), earliestStart.getEnd() + 1);

	if (associatedWindows.size() > 1) {
		callback.merge(target, associatedWindows);
	}
}
 
Example 2
Source File: TestExplicitColumnTracker.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSingleVersion() throws IOException {
  // Create tracker
  TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR);
  // Looking for every other
  columns.add(col2);
  columns.add(col4);
  List<MatchCode> expected = new ArrayList<>(5);
  expected.add(ScanQueryMatcher.MatchCode.SEEK_NEXT_COL); // col1
  expected.add(ScanQueryMatcher.MatchCode.INCLUDE_AND_SEEK_NEXT_COL); // col2
  expected.add(ScanQueryMatcher.MatchCode.SEEK_NEXT_COL); // col3
  expected.add(ScanQueryMatcher.MatchCode.INCLUDE_AND_SEEK_NEXT_ROW); // col4
  expected.add(ScanQueryMatcher.MatchCode.SEEK_NEXT_ROW); // col5
  int maxVersions = 1;

  // Create "Scanner"
  List<byte[]> scanner = new ArrayList<>(5);
  scanner.add(col1);
  scanner.add(col2);
  scanner.add(col3);
  scanner.add(col4);
  scanner.add(col5);

  runTest(maxVersions, columns, scanner, expected);
}
 
Example 3
Source File: TimePickerSettings.java    From LGoodDatePicker with MIT License 6 votes vote down vote up
/**
 * generatePotentialMenuTimes, This will generate the menu times for populating the combo box
 * menu, using the items from a list of LocalTime instances. The list will be sorted and cleaned
 * of duplicates before use. Null values and duplicate values will not be added. When this
 * function is complete, the menu will contain one instance of each unique LocalTime that was
 * supplied to this function, in ascending order going from Midnight to 11.59pm. The drop down
 * menu will not contain any time values except those supplied in the desiredTimes list.
 *
 * Note: This function can be called before or after setting an optional veto policy. Vetoed
 * times will never be added to the time picker menu, regardless of whether they are generated
 * by this function.
 */
public void generatePotentialMenuTimes(ArrayList<LocalTime> desiredTimes) {
    potentialMenuTimes = new ArrayList<LocalTime>();
    if (desiredTimes == null || desiredTimes.isEmpty()) {
        return;
    }
    TreeSet<LocalTime> timeSet = new TreeSet<LocalTime>();
    for (LocalTime desiredTime : desiredTimes) {
        if (desiredTime != null) {
            timeSet.add(desiredTime);
        }
    }
    for (LocalTime timeSetEntry : timeSet) {
        potentialMenuTimes.add(timeSetEntry);
    }
}
 
Example 4
Source File: TreeSetTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * iterator.remove removes current element
 */
public void testIteratorRemove() {
    final TreeSet q = new TreeSet();
    q.add(new Integer(2));
    q.add(new Integer(1));
    q.add(new Integer(3));

    Iterator it = q.iterator();
    it.next();
    it.remove();

    it = q.iterator();
    assertEquals(it.next(), new Integer(2));
    assertEquals(it.next(), new Integer(3));
    assertFalse(it.hasNext());
}
 
Example 5
Source File: SolverGroup.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static TreeSet<SolverGroup> getUserSolverGroups(UserContext user) {
	TreeSet<SolverGroup> solverGroups = new TreeSet<SolverGroup>();
	if (user == null || user.getCurrentAuthority() == null) return solverGroups;
	if (user.getCurrentAuthority().hasRight(Right.DepartmentIndependent))
		solverGroups.addAll(SolverGroup.findBySessionId(user.getCurrentAcademicSessionId()));
	else
		for (UserQualifier q: user.getCurrentAuthority().getQualifiers("SolverGroup"))
			solverGroups.add(SolverGroupDAO.getInstance().get((Long)q.getQualifierId()));
	return solverGroups;
}
 
Example 6
Source File: DefaultFormatService.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String[] getSuffixes() {
	final TreeSet<String> ts = new TreeSet<>();

	for (final Format f : formats()) {
		for (final String s : f.getSuffixes()) {
			ts.add(s);
		}
	}

	return ts.toArray(new String[ts.size()]);
}
 
Example 7
Source File: ConcurrentLRUCache.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Returns 'n' number of oldest accessed entries present in this cache.
 *
 * This uses a TreeSet to collect the 'n' oldest items ordered by ascending last access time
 *  and returns a LinkedHashMap containing 'n' or less than 'n' entries.
 * @param n the number of oldest items needed
 * @return a LinkedHashMap containing 'n' or less than 'n' entries
 */
public Map<K, V> getOldestAccessedItems(int n) {
  Map<K, V> result = new LinkedHashMap<>();
  if (n <= 0)
    return result;
  TreeSet<CacheEntry<K,V>> tree = new TreeSet<>();
  markAndSweepLock.lock();
  try {
    for (Map.Entry<Object, CacheEntry<K,V>> entry : map.entrySet()) {
      CacheEntry<K,V> ce = entry.getValue();
      ce.lastAccessedCopy = ce.lastAccessed;
      if (tree.size() < n) {
        tree.add(ce);
      } else {
        if (ce.lastAccessedCopy < tree.first().lastAccessedCopy) {
          tree.remove(tree.first());
          tree.add(ce);
        }
      }
    }
  } finally {
    markAndSweepLock.unlock();
  }
  for (CacheEntry<K,V> e : tree) {
    result.put(e.key, e.value);
  }
  return result;
}
 
Example 8
Source File: BeanMappingFactoryHelper.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * カラム番号が重複しているかチェックする。また、番号が1以上かもチェックする。
 * @param beanType Beanタイプ
 * @param list カラム情報の一覧
 * @return チェック済みの番号
 * @throws SuperCsvInvalidAnnotationException {@link CsvColumn}の定義が間違っている場合
 */
public static TreeSet<Integer> validateDuplicatedColumnNumber(final Class<?> beanType, final List<ColumnMapping> list) {
    
    final TreeSet<Integer> checkedNumber = new TreeSet<>();
    final TreeSet<Integer> duplicatedNumbers = new TreeSet<>();
    for(ColumnMapping columnMapping : list) {
        
        if(checkedNumber.contains(columnMapping.getNumber())) {
            duplicatedNumbers.add(columnMapping.getNumber());
        }
        checkedNumber.add(columnMapping.getNumber());
        
    }
    
    if(!duplicatedNumbers.isEmpty()) {
        // 重複している 属性 numberが存在する場合
        throw new SuperCsvInvalidAnnotationException(MessageBuilder.create("anno.attr.duplicated")
                .var("property", beanType.getName())
                .varWithAnno("anno", CsvColumn.class)
                .var("attrName", "number")
                .var("attrValues", duplicatedNumbers)
                .format());
    }
    
    // カラム番号が1以上かチェックする
    final int minColumnNumber = checkedNumber.first();
    if(minColumnNumber <= 0) {
        throw new SuperCsvInvalidAnnotationException(MessageBuilder.create("anno.attr.min")
                .var("property", beanType.getName())
                .varWithAnno("anno", CsvColumn.class)
                .var("attrName", "number")
                .var("attrValue", minColumnNumber)
                .var("min", 1)
                .format());
        
    }
    
    return checkedNumber;
}
 
Example 9
Source File: TreeSetTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * add(null) throws NPE if nonempty
 */
public void testAddNull() {
    TreeSet q = populatedSet(SIZE);
    try {
        q.add(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 10
Source File: Util.java    From dictomaton with Apache License 2.0 5 votes vote down vote up
public static SortedSet<String> loadWordList(String resourceName) throws IOException {
    InputStream in = ClassLoader.getSystemResourceAsStream(resourceName);

    TreeSet<String> words = new TreeSet<>();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        String line;
        while ((line = reader.readLine()) != null) {
            words.add(line.trim());
        }

    }

    return words;
}
 
Example 11
Source File: LabelImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Replace all values specified in label array by a new value.
 *  
 * @param image a label 3D image
 * @param labels the list of labels to replace 
 * @param newLabel the new value for labels 
 */
public static final void replaceLabels(ImageStack image, int[] labels, int newLabel)
{
	int sizeX = image.getWidth();
	int sizeY = image.getHeight();
	int sizeZ = image.getSize();
	
	TreeSet<Integer> labelSet = new TreeSet<Integer>();
	for (int i = 0; i < labels.length; i++) 
	{
		labelSet.add(labels[i]);
	}
	
	for (int z = 0; z < sizeZ; z++) 
	{
		for (int y = 0; y < sizeY; y++)
		{
			for (int x = 0; x < sizeX; x++) 
			{
				int value = (int) image.getVoxel(x, y, z); 
				if (value == newLabel)
					continue;
				if (labelSet.contains(value)) 
					image.setVoxel(x, y, z, newLabel);
			}
		}
	}
}
 
Example 12
Source File: GenericObjectCompareToTest.java    From sofa-hessian with Apache License 2.0 5 votes vote down vote up
@Test
public void testTreeSet() throws Exception {
    TreeSet<GenericObject> treeSet = new TreeSet<GenericObject>();
    SimplePerson person = new SimplePerson();
    person.setJob("coder");
    treeSet.add((GenericObject) GenericUtils.convertToGenericObject(person));

    person = new SimplePerson();
    person.setName("zhangsan");
    treeSet.add((GenericObject) GenericUtils.convertToGenericObject(person));

    assertTrue(treeSet.size() == 2);

    person = new SimplePerson();
    person.setName("lisi");
    treeSet.add((GenericObject) GenericUtils.convertToGenericObject(person));

    person = new SimplePerson();
    person.setName("zhangsan");
    treeSet.add((GenericObject) GenericUtils.convertToGenericObject(person));

    assertTrue(treeSet.size() == 3);

    person = new SimplePerson();
    person.setName("lisi");
    person.setJob("coder");
    treeSet.add((GenericObject) GenericUtils.convertToGenericObject(person));
    assertTrue(treeSet.size() == 4);

    person = new SimplePerson();
    person.setName("lisi");
    person.setJob("coder");
    treeSet.add((GenericObject) GenericUtils.convertToGenericObject(person));
    assertTrue(treeSet.size() == 4);
}
 
Example 13
Source File: WeightedCollectionTest.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testArchitectureProof()
{
	TreeSet<String> ciSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
	TreeSet<String> csSet = new TreeSet<>(String::compareTo);
	//To prove existing behavior
	assertEquals(ciSet, csSet);
	ciSet.add("asting");
	csSet.add("asting");
	ciSet.add("aString");
	csSet.add("aString");
	assertEquals(ciSet, csSet);
	assertNotEquals(ciSet.toString(), csSet.toString());
}
 
Example 14
Source File: Solution.java    From java-technology-stack with MIT License 5 votes vote down vote up
public int findCircleNum(int[][] M) {

        int n = M.length;
        UnionFind6 uf = new UnionFind6(n);
        for(int i = 0 ; i < n ; i ++)
            for(int j = 0 ; j < i ; j ++)
                if(M[i][j] == 1)
                    uf.unionElements(i, j);

        TreeSet<Integer> set = new TreeSet<>();
        for(int i = 0 ; i < n ; i ++)
            set.add(uf.find(i));
        return set.size();
    }
 
Example 15
Source File: ShowTables.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private static Set<String> getTableSet(ServerConnection c, Map<String, String> parm)
{
    TreeSet<String> tableSet = new TreeSet<String>();
    MycatConfig conf = MycatServer.getInstance().getConfig();

    Map<String, UserConfig> users = conf.getUsers();
    UserConfig user = users == null ? null : users.get(c.getUser());
    if (user != null) {


        Map<String, SchemaConfig> schemas = conf.getSchemas();
        for (String name:schemas.keySet()){
            if (null !=parm.get(SCHEMA_KEY) && parm.get(SCHEMA_KEY).toUpperCase().equals(name.toUpperCase())  ){

                if(null==parm.get("LIKE_KEY")){
                    tableSet.addAll(schemas.get(name).getTables().keySet());
                }else{
                    String p = "^" + parm.get("LIKE_KEY").replaceAll("%", ".*");
                    Pattern pattern = Pattern.compile(p,Pattern.CASE_INSENSITIVE);
                    Matcher ma ;

                    for (String tname : schemas.get(name).getTables().keySet()){
                        ma=pattern.matcher(tname);
                        if(ma.matches()){
                            tableSet.add(tname);
                        }
                    }

                }

            }
        };



    }
    return tableSet;
}
 
Example 16
Source File: DumpSetAsSequenceExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
private Blog createBlog() {
    Blog blog = new Blog("Test Me!");
    blog.addPost(new Post("Title1", "text 1"));
    blog.addPost(new Post("Title2", "text text 2"));
    blog.numbers.add(19);
    blog.numbers.add(17);
    TreeSet<String> labels = new TreeSet<String>();
    labels.add("Java");
    labels.add("YAML");
    labels.add("SnakeYAML");
    blog.setLabels(labels);
    return blog;
}
 
Example 17
Source File: ColumnManage.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 递归获取所有栏目Id
 * @param columnList
 * @param id
 * @return
 */
public TreeSet<Integer> columnIdList(List<Column> columnList,TreeSet<Integer> id){
	if(columnList != null && columnList.size() >0){
		for(Column column : columnList){
			id.add(column.getId());
			if(column.getChildColumn() != null && column.getChildColumn().size() >0){
				columnIdList(column.getChildColumn(),id);
			}
			
		}
	}
	return id;
}
 
Example 18
Source File: PreferenceGroup.java    From unitime with Apache License 2.0 5 votes vote down vote up
public Set getTimePatterns() {
	Set timePrefs = getTimePreferences();
	if (timePrefs==null) return null;
	TreeSet ret = new TreeSet();
	for (Iterator i=timePrefs.iterator();i.hasNext();) {
		TimePref tp = (TimePref)i.next();
		if (tp.getTimePattern()!=null)
			ret.add(tp.getTimePattern());
	}
	return ret;
}
 
Example 19
Source File: Phase3Step3NearDupTuplesCreation.java    From dkpro-c4corpus with Apache License 2.0 4 votes vote down vote up
@Override
protected void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException
{

    //get the file name
    FileSplit fileSplit = (FileSplit) context.getInputSplit();
    String fileName = fileSplit.getPath().getName();

    //process text as docInfo enteries 
    String[] documents = value.toString().split(",");

    List<String> similarCandidates = new ArrayList<>(Arrays.asList(documents));

    for (int i = 0; i < similarCandidates.size() - 1; i++) {

        //process the head doc
        DocumentInfo headDoc = new DocumentInfo();
        headDoc.createDocumentInfo(similarCandidates.get(i));
        long headDocSimHash = headDoc.getDocSimHash().get();
        //other candidates
        for (int j = i + 1; j < similarCandidates.size(); j++) {
            DocumentInfo similarDoc = new DocumentInfo();
            similarDoc.createDocumentInfo(similarCandidates.get(j));
            long similarDocSimHash = similarDoc.getDocSimHash().get();

            //calc the hamming distance
            int hammingDist = SimHashUtils.diffOfBits(headDocSimHash, similarDocSimHash);
            //if the hamming distance is <=3
            if (hammingDist <= SimHashUtils.HAMMING_DISTANCE_THRESHOLD) {
                //save the doc in one cluster
                //the Document datastructure must implement a compare method
                //in order to be able to add the document iinto the TreeSet
                TreeSet<DocumentInfo> cluster = new TreeSet<>();
                cluster.add(headDoc);
                cluster.add(similarDoc);
                if (cluster.size() > 1) {
                    //                            context.write(NullWritable.get(), cluster);
                    multipleOutputs.write(NullWritable.get(), cluster, fileName);
                }
            }
        }
    }
}
 
Example 20
Source File: TransactionStateService.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
private void recreateStateTable() {
    this.tranStateTable =
            new MapedFileQueue(defaultMessageStore.getMessageStoreConfig().getTranStateTableStorePath(),
                defaultMessageStore.getMessageStoreConfig().getTranStateTableMapedFileSize(), null);

    final TreeSet<Long> preparedItemSet = new TreeSet<Long>();

    final long minOffset = this.tranRedoLog.getMinOffsetInQuque();
    long processOffset = minOffset;
    while (true) {
        SelectMapedBufferResult bufferConsumeQueue = this.tranRedoLog.getIndexBuffer(processOffset);
        if (bufferConsumeQueue != null) {
            try {
                long i = 0;
                for (; i < bufferConsumeQueue.getSize(); i += ConsumeQueue.CQStoreUnitSize) {
                    long offsetMsg = bufferConsumeQueue.getByteBuffer().getLong();
                    int sizeMsg = bufferConsumeQueue.getByteBuffer().getInt();
                    long tagsCode = bufferConsumeQueue.getByteBuffer().getLong();

                    // Prepared
                    if (TransactionStateService.PreparedMessageTagsCode == tagsCode) {
                        preparedItemSet.add(offsetMsg);
                    }
                    // Commit/Rollback
                    else {
                        preparedItemSet.remove(tagsCode);
                    }
                }

                processOffset += i;
            }
            finally {
                bufferConsumeQueue.release();
            }
        }
        else {
            break;
        }
    }

    log.info("scan transaction redolog over, End offset: {},  Prepared Transaction Count: {}",
        processOffset, preparedItemSet.size());

    Iterator<Long> it = preparedItemSet.iterator();
    while (it.hasNext()) {
        Long offset = it.next();

        MessageExt msgExt = this.defaultMessageStore.lookMessageByOffset(offset);
        if (msgExt != null) {

            this.appendPreparedTransaction(msgExt.getCommitLogOffset(), msgExt.getStoreSize(),
                (int) (msgExt.getStoreTimestamp() / 1000),
                msgExt.getProperty(MessageConst.PROPERTY_PRODUCER_GROUP).hashCode());
            this.tranStateTableOffset.incrementAndGet();
        }
    }
}