java.util.Collections#sort ( )源码实例Demo

下面列出了java.util.Collections#sort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void testB()
{
    DataSet dsA = new DataSet( "EA: Expenditures Site Level", new QuarterlyPeriodType() );
    DataSet dsB = new DataSet( "MER Results: Facility Based", new QuarterlyPeriodType() );
    DataSet dsC = new DataSet( "MER Results: Facility Based - DoD ONLY", new QuarterlyPeriodType() );

    DataApprovalWorkflow workflow = new DataApprovalWorkflow( "Workflow A", new QuarterlyPeriodType(), null );

    dsB.assignWorkflow( workflow );

    List<DataSet> list = Lists.newArrayList( dsB, dsC, dsA );

    Collections.sort( list, DataSetApprovalFrequencyComparator.INSTANCE );

    assertEquals( dsB, list.get( 0 ) );
    assertEquals( dsA, list.get( 1 ) );
    assertEquals( dsC, list.get( 2 ) );
}
 
源代码2 项目: HttpInfo   文件: MtuHelper.java
public static void getMtuParam() throws Exception {
    long startTime = LogTime.getLogTime();
    MtuScan mtuScan = new MtuScan(Base.getUrlHost());
    List<Integer> mtuList = mtuScan.startReturnValue();
    MtuBean mtuBean = new MtuBean();
    if (mtuList.size() == 0) {
        mtuBean.setStatus(BaseData.HTTP_ERROR);
    } else {
        mtuBean.setStatus(BaseData.HTTP_SUCCESS);
        Collections.sort(mtuList);
        mtuBean.setMtu(mtuList.get(mtuList.size() - 1) + 28);
    }
    mtuScan.cancelMtuScan();
    mtuBean.setTotalTime(LogTime.getElapsedMillis(startTime));
    HttpLog.i("MtuScan is end");
    Input.onSuccess(HttpType.MTU_SCAN, mtuBean.toJSONObject());
}
 
源代码3 项目: Doradus   文件: AmazonS3Service.java
@Override
public List<DColumn> getColumns(String storeName, String rowKey, Collection<String> columnNames) {
    String namespace = getTenant().getName();
    List<Future<?>> futures = new ArrayList<>();
    final ArrayList<DColumn> list = new ArrayList<>();
    final String path = namespace + "/" + storeName + "/" + encode(rowKey) + "/";
    for(String columnName: columnNames) {
        futures.add(s3_executor.submit(new Runnable() {
            @Override public void run() {
                byte[] value = m_connection.get(path + encode(columnName));
                if(value != null) {
                    synchronized (list) {
                        list.add(new DColumn(columnName, value));
                    }
                }
            }
        }));
    }
    wait(futures);
    Collections.sort(list);
    return list;
}
 
源代码4 项目: landlord_client   文件: LandlordUtil.java
/**
 *判断串联三代二,二必须是对子。是就返回牌面,不是就返回-1
 */
private static List<Integer> getMultiThreeWithTwo(List<Integer> cards) {
    ArrayList<Integer> copy = getRealCards(cards);
    HashSet<Integer> set = new HashSet<>();
    boolean isFullHouse = false;
    boolean isAllCouple = false;
    for(Integer card : copy) {
        if(Collections.frequency(copy, card) == 3) set.add(card);
        if(Collections.frequency(copy, card) == 2) isAllCouple = true;
        if(Collections.frequency(copy, card) == 1 || Collections.frequency(copy, card) == 4) {
            isAllCouple = false;
            break;
        }
    }
    List<Integer> three = new ArrayList<>(set);
    Collections.sort(three);
    for(int i = three.size() - 1; i > 0; i--) {
        if(three.get(i) - three.get(i-1) == 1) isFullHouse = true;
        else {
            isFullHouse = false;
            break;
        }
    }
    if(cards.size() % 5 != 0 || cards.size() <= 5 || cards.size() / 5 != three.size() || !isFullHouse || !isAllCouple) return null;
    return three;
}
 
源代码5 项目: sqlitemagic   文件: TestUtil.java
public static List<ComplexObjectWithSameLeafs> insertComplexValuesWithSameLeafs(int count) {
  final Transaction transaction = SqliteMagic.newTransaction();
  try {
    final ArrayList<ComplexObjectWithSameLeafs> values = new ArrayList<>(count);
    for (int i = 0; i < count; i++) {
      ComplexObjectWithSameLeafs a = ComplexObjectWithSameLeafs.newRandom();
      assertThat(a.persist().execute()).isNotEqualTo(-1);
      values.add(a);
    }
    Collections.sort(values, new Comparator<ComplexObjectWithSameLeafs>() {
      @Override
      public int compare(ComplexObjectWithSameLeafs lhs, ComplexObjectWithSameLeafs rhs) {
        return Long.valueOf(lhs.id).compareTo(rhs.id);
      }
    });
    transaction.markSuccessful();
    return values;
  } finally {
    transaction.end();
  }
}
 
源代码6 项目: DominionSim   文件: ReplaceCard.java
public void play() {
   if (owner.getCardsInHand().isEmpty())
 	return;
   if (owner.isHumanOrPossessedByHuman()) {
       handleHumanPlayer();
       return;
   }

   DomCard theCardToTrash = owner.findCardToRemodel(this, 2, true);
   if (theCardToTrash==null) {
     //this is needed when card is played with Throne Room effect
     Collections.sort(owner.getCardsInHand(),SORT_FOR_TRASHING);
     theCardToTrash=owner.getCardsInHand().get(0);
   }
   owner.trash(owner.removeCardFromHand( theCardToTrash));
   DomCost theMaxCostOfCardToGain = new DomCost( theCardToTrash.getCoinCost(owner.getCurrentGame()) + 2, theCardToTrash.getPotionCost());
DomCardName theDesiredCard = owner.getDesiredCard(theMaxCostOfCardToGain, false);
   if (theDesiredCard==null)
 	theDesiredCard=owner.getCurrentGame().getBestCardInSupplyFor(owner, null, theMaxCostOfCardToGain);
   if (theDesiredCard!=null) {
       if (theDesiredCard.hasCardType(DomCardType.Action) || theDesiredCard.hasCardType(DomCardType.Treasure)) {
           owner.gainOnTopOfDeck(owner.getCurrentGame().takeFromSupply(theDesiredCard));
       }else {
           owner.gain(theDesiredCard);
           if (theDesiredCard.hasCardType(DomCardType.Victory))
               distributeCurses();
       }
   }
 }
 
源代码7 项目: jamel   文件: BasicWorker.java
/**
 * Chooses a job among the received job offers.
 */
public void chooseJob() {
	if (jobOffers.size() > 0) {
		Collections.sort(jobOffers, jobComparator);
		final JobOffer jobOffer = jobOffers.get(0);
		if (jobOffer.size() > 0 && jobOffer.getWage() >= reservationWage) {
			this.jobContract = jobOffer.apply(this);
			this.unempDuration = 0;
		}
	}
}
 
@Override
@Label("BinaryOperationSuffix Expression")
public Rule ExpressionRule() {
    Rule initialExpression = EMPTY;
    ImmutableListMultimap<Integer, BinaryOperator> index = Multimaps.index(operators, precedence());

    List<Integer> integers = new ArrayList<>(index.keySet());
    Collections.sort(integers);
    for (Integer integer : integers) {
        initialExpression = BinaryOperation(initialExpression, index.get(integer));
    }
    return initialExpression;
}
 
源代码9 项目: NBTEditor   文件: AbstractNBTCommand.java
private static List<String> getVariableNames(BaseNBT base, String prefix) {
	List<String> names = new ArrayList<String>();
	for (NBTVariableContainer container : base.getAllVariables()) {
		for (String name : container.getVariableNames()) {
			if (StringUtil.startsWithIgnoreCase(name, prefix)) {
				names.add(name);
			}
		}
	}
	Collections.sort(names, String.CASE_INSENSITIVE_ORDER);
	return names;
}
 
源代码10 项目: helix   文件: AutoRebalanceStrategy.java
/**
 * Move replicas from too-full nodes to nodes that can accept the replicas
 */
private void moveExcessReplicas() {
  // iterate over nodes and move extra load
  Iterator<Replica> it;
  for (Node donor : _liveNodesList) {
    if (donor.capacity < donor.currentlyAssigned) {
      Collections.sort(donor.nonPreferred);
      it = donor.nonPreferred.iterator();
      while (it.hasNext()) {
        Replica replica = it.next();
        int startIndex = computeRandomStartIndex(replica);
        for (int index = startIndex; index < startIndex + _liveNodesList.size(); index++) {
          Node receiver = _liveNodesList.get(index % _liveNodesList.size());
          if (receiver.canAdd(replica)) {
            receiver.currentlyAssigned = receiver.currentlyAssigned + 1;
            receiver.nonPreferred.add(replica);
            donor.currentlyAssigned = donor.currentlyAssigned - 1;
            it.remove();
            break;
          }
        }
        if (donor.capacity >= donor.currentlyAssigned) {
          break;
        }
      }
      if (donor.capacity < donor.currentlyAssigned) {
        logger.warn("Could not take partitions out of node:" + donor.id);
      }
    }
  }
}
 
源代码11 项目: ache   文件: PersistentHashtable.java
@Deprecated
public synchronized List<Tuple<T>> orderedSet(final Comparator<T> valueComparator) {
    try {
        List<Tuple<T>> elements = getTable();
        Collections.sort(elements, new Comparator<Tuple<T>>() {
            @Override
            public int compare(Tuple<T> o1, Tuple<T> o2) {
                return valueComparator.compare(o1.getValue(), o2.getValue());
            }
        });
        return elements;
    } catch (Exception e) {
        throw new RuntimeException("Failed to list elements from hashtable.", e);
    }
}
 
源代码12 项目: Knowage-Server   文件: Node.java
public void addOrderedChild(Node child, Comparator<Node> comp) {
	childs.add(child);
	child.fatherNode = this;
	if (childs != null) {
		if (comp == null)
			Collections.sort(childs);
		else
			Collections.sort(childs, comp);
	}
}
 
源代码13 项目: jdk8u-dev-jdk   文件: Package.java
void reorderFiles(boolean keepClassOrder, boolean stripDirectories) {
    // First reorder the classes, if that is allowed.
    if (!keepClassOrder) {
        // In one test with rt.jar, this trick gained 0.7%
        Collections.sort(classes);
    }

    // Remove stubs from resources; maybe we'll add them on at the end,
    // if there are some non-trivial ones.  The best case is that
    // modtimes and options are not transmitted, and the stub files
    // for class files do not need to be transmitted at all.
    // Also
    List<File> stubs = getClassStubs();
    for (Iterator<File> i = files.iterator(); i.hasNext(); ) {
        File file = i.next();
        if (file.isClassStub() ||
            (stripDirectories && file.isDirectory())) {
            i.remove();
        }
    }

    // Sort the remaining non-class files.
    // We sort them by file type.
    // This keeps files of similar format near each other.
    // Put class files at the end, keeping their fixed order.
    // Be sure the JAR file's required manifest stays at the front. (4893051)
    Collections.sort(files, new Comparator<File>() {
            public int compare(File r0, File r1) {
                // Get the file name.
                String f0 = r0.nameString;
                String f1 = r1.nameString;
                if (f0.equals(f1)) return 0;
                if (JarFile.MANIFEST_NAME.equals(f0))  return 0-1;
                if (JarFile.MANIFEST_NAME.equals(f1))  return 1-0;
                // Extract file basename.
                String n0 = f0.substring(1+f0.lastIndexOf('/'));
                String n1 = f1.substring(1+f1.lastIndexOf('/'));
                // Extract basename extension.
                String x0 = n0.substring(1+n0.lastIndexOf('.'));
                String x1 = n1.substring(1+n1.lastIndexOf('.'));
                int r;
                // Primary sort key is file extension.
                r = x0.compareTo(x1);
                if (r != 0)  return r;
                r = f0.compareTo(f1);
                return r;
            }
        });

    // Add back the class stubs after sorting, before trimStubs.
    files.addAll(stubs);
}
 
源代码14 项目: home-assistant-Android   文件: HassUtils.java
public static void extractGroups(@NonNull Map<String, Entity> entityMap, List<Pair<Entity, List<Entity>>> entities, boolean extractDefaultGroups) {
    entities.clear();
    for (Entity entity : entityMap.values()) {
        if (entity.getDomain().equals(GROUP)) {
            if (entity.isHidden()) {
                if (extractDefaultGroups && entity.getName().length() > 5 && entity.getName().startsWith("all_")) {
                    String name = Character.toUpperCase(entity.getName().charAt(4)) + entity.getName().substring(5);
                    entity.attributes.put(Attribute.FRIENDLY_NAME, name);
                } else {
                    continue;
                }
            }

            // Add group children
            List<String> entityIds = entity.attributes.getList(Attribute.ENTITY_ID, String.class);
            if (entityIds == null) {
                continue;
            }
            List<Entity> children = new ArrayList<>();
            for (String childrenKey : entityIds) {
                Entity child = entityMap.get(childrenKey);
                if (child == null || child.isHidden()) continue;
                if (child.type == EntityType.GROUP)
                    child.type = child.attributes.getString(Attribute.CONTROL) == null ? EntityType.SWITCH : EntityType.TEXT;
                children.add(child);
            }
            entities.add(new Pair<>(entity, children));
        }
    }

    // If list is still empty, try extracting the default groups
    if (entities.isEmpty() && !extractDefaultGroups) {
        extractGroups(entityMap, entities, true);
        return;
    }

    /*
    // Create additional group for media players
    Entity mediaPlayersGroup = new Entity();
    mediaPlayersGroup.id = GROUP + ".players";
    mediaPlayersGroup.attributes = new Ason();
    mediaPlayersGroup.applyType();
    List<Entity> mediaPlayers = new ArrayList<>();
    for (Entity entity : entityMap.values()) {
        System.out.println(entity.id);
        if (entity.getDomain().equals(MEDIA_PLAYER))
            mediaPlayers.add(entity);
    }
    entities.add(new Pair<>(mediaPlayersGroup, mediaPlayers));*/

    // Sort groups according to their order number
    //noinspection Java8ListSort,ComparatorCombinators
    Collections.sort(entities, (o1, o2) -> o1.first.compareTo(o2.first));
}
 
源代码15 项目: abra2   文件: JunctionUtils.java
/**
 * Load junctions from GTF using exons grouped by transcript_id
 * Sort order is unspecified 
 */
public static Set<Feature> loadJunctionsFromGtf(String filename) throws FileNotFoundException, IOException {
	Logger.debug("Loading annotated junctions from %s", filename);
	Set<Exon> exonSet = new HashSet<Exon>();
	
	BufferedReader reader = new BufferedReader(new FileReader(filename));
	
	try {
		String line = reader.readLine();
		while (line != null) {
			if (!line.startsWith("#")) {
				String[] fields = line.split("\\t");
				if (fields.length >= 9 && fields[2].equals("exon")) {
					String chrom = fields[0];
					int start = Integer.parseInt(fields[3]);
					int stop = Integer.parseInt(fields[4]);
					String attributes = fields[8];
					String[] attrFields = attributes.split(";");
					for (String attr : attrFields) {
						attr = attr.trim();
						if (attr.startsWith("transcript_id")) {
							int idx = attr.indexOf("transcript_id") + "transcript_id".length();
							String transcriptId = attr.substring(idx, attr.length());
							exonSet.add(new Exon(chrom, start, stop, transcriptId));
						}
					}
				}
			}
			
			line = reader.readLine();
		}
	} finally {
		reader.close();
	}
	
	List<Exon> exons = new ArrayList<Exon>(exonSet);
	Collections.sort(exons);
	
	Set<Feature> junctions = new HashSet<Feature>();
	Exon prevExon = null;
	
	for (Exon exon : exons) {
		if (prevExon != null && exon.getTranscriptId().equals(prevExon.getTranscriptId())) {
			// Create junction, adjusting coordinates to match first / last position in intron
			// similar to STAR's junction output
			Feature junction = new Feature(exon.getChrom(), prevExon.getStop()+1, exon.getStart()-1);
			junctions.add(junction);
		}
		
		prevExon = exon;
	}
	
	Logger.info("Loaded " + junctions.size() + " annotated junctions");
	
	return junctions;
}
 
源代码16 项目: jdk8u-dev-jdk   文件: Rdn.java
void sort() {
    if (entries.size() > 1) {
        Collections.sort(entries);
    }
}
 
@Override
public Object provide(Object source, Object current) {
    List<AcademicInterval> result = AcademicInterval.readActiveAcademicIntervals(AcademicPeriod.YEAR);
    Collections.sort(result, AcademicInterval.COMPARATOR_BY_BEGIN_DATE);
    return result;
}
 
源代码18 项目: the-one   文件: MaxPropRouter.java
/**
 * Tries to send all other messages to all connected hosts ordered by
 * hop counts and their delivery probability
 * @return The return value of {@link #tryMessagesForConnected(List)}
 */
private Tuple<Message, Connection> tryOtherMessages() {
	List<Tuple<Message, Connection>> messages =
		new ArrayList<Tuple<Message, Connection>>();

	Collection<Message> msgCollection = getMessageCollection();

	/* for all connected hosts that are not transferring at the moment,
	 * collect all the messages that could be sent */
	for (Connection con : getConnections()) {
		DTNHost other = con.getOtherNode(getHost());
		MaxPropRouter othRouter = (MaxPropRouter)other.getRouter();
		Set<String> sentMsgIds = this.sentMessages.get(other);

		if (othRouter.isTransferring()) {
			continue; // skip hosts that are transferring
		}

		for (Message m : msgCollection) {
			/* skip messages that the other host has or that have
			 * passed the other host */
			if (othRouter.hasMessage(m.getId()) ||
					m.getHops().contains(other)) {
				continue;
			}
			/* skip message if this host has already sent it to the other
			   host (regardless of if the other host still has it) */
			if (sentMsgIds != null && sentMsgIds.contains(m.getId())) {
				continue;
			}
			/* message was a good candidate for sending */
			messages.add(new Tuple<Message, Connection>(m,con));
		}
	}

	if (messages.size() == 0) {
		return null;
	}

	/* sort the message-connection tuples according to the criteria
	 * defined in MaxPropTupleComparator */
	Collections.sort(messages, new MaxPropTupleComparator(calcThreshold()));
	return tryMessagesForConnected(messages);
}
 
源代码19 项目: SDA   文件: SparqlFusekiQueryImpl.java
/**
 * 여러개의 값에서 값을 추출
 * @param queryList
 * @param idxVals
 * @throws Exception
 * @return List<Map<String,String>>
 */
private List<Map<String, String>> getUniqueResultBySameColumn(List<String> queryList, String[] idxVals) throws Exception {

	// queryList의 쿼리를 수행한 결과를 모두 담고 있는 List
	List<List<Map<String, String>>> query_result_list = new ArrayList<List<Map<String, String>>>();

	// queryList한개의 수행결과를 담고 있는 List
	List<Map<String, String>> query_result;

	boolean haveNullResult = false;

	// 쿼리를 실행해서 구분자로 분리하여 list에 담는다.
	for (int i = 0; i < queryList.size(); i++) {
		query_result = runQuery(queryList.get(i), idxVals);
		log.debug("query result[" + i + "]  =========> \n" + query_result.toString());
		
		if (query_result.size() == 0) {
			haveNullResult = true;
			log.debug("this query result has null, so it will break out loop without running rest query .............");
			break;
		} else {
			query_result = distinctList(query_result);
			log.debug("distinct query result[" + i + "]  =========> \n" + query_result.toString());
			
			query_result_list.add(query_result);
			log.debug("result added of query_result.size() : " + query_result.size());
		}
	}
	
	log.debug("query_result_list ==>" + query_result_list);
	
	// 결과값의 전체 개수
	int total_query_result_list_count = query_result_list.size();

	// 제일 작은 개수를 찾기위해서 개수및 idx 만으로 이루어진 임시 List를 만듬
	List<IdxCnt> cntList = new ArrayList<IdxCnt>();

	if (haveNullResult == false) {
		for (int i = 0; i < query_result_list.size(); i++) {
			IdxCnt cnt = new IdxCnt();
			cnt.setCnt(query_result_list.get(i).size());
			cnt.setIdx(i);
			cntList.add(cnt);
		}
	}
	
	log.debug("cntList =========> " + cntList);
	
	// return할 최종결과 List
	List<Map<String, String>> returnList = new ArrayList<Map<String, String>>();
	int matchedRowCnt = 0;
	// 건수가 제일 작은 것을 기준으로 찾아야함.
	if (haveNullResult == false && total_query_result_list_count > 1) {
		Collections.sort(cntList, new CntCompare());
		int idx = cntList.get(0).getIdx(); 			// 개수가 제일 작은것을 찾는다.
		List<Map<String, String>> stdList = query_result_list.get(idx); // 비교시 기준이 되는 List를 추출한다.
		query_result_list.remove(idx); 				// idx에 속하는 List는 제거하여 중복체크되지 않도록 함

		log.debug("stdList =========> " + stdList.toString());
		log.debug("removed query_result_list ==>" + query_result_list);
		
		// 제일 작은 개수 List를 기준으로 체크한다.
		for (int i = 0; i < stdList.size(); i++) {
			matchedRowCnt = 0;
			log.debug("stdList.get(" + i + ") :"+stdList.get(i));
			for (int k = 0; k < query_result_list.size(); k++) {
				log.debug("query_result_list.get(" + k + ") :" +query_result_list.get(k));
				
				if (query_result_list.get(k).contains(stdList.get(i))) {
					matchedRowCnt++;
					log.debug("query_result_list.get(" + k + ").contains(stdList.get(" + i + ")) == true");
				}
			} // 내부 순환 end
			log.debug("matchedRowCnt of "+stdList.get(i)+" ===> "+matchedRowCnt);
			if(matchedRowCnt == (total_query_result_list_count-1)) {
				returnList.add(stdList.get(i));
			}
		}
	} else if (haveNullResult == false && total_query_result_list_count  == 1) {      // 결과값이 1개의 row만을 가지고 있으면 내부 값을 모두 리턴해줌
		log.debug("total_query_result_list_count is 1  =========> " + query_result_list.get(0));
		returnList = query_result_list.get(0);
	} else {
		// pass
	}
	
	return distinctList(returnList);
}
 
源代码20 项目: AndroidRipper   文件: RobotiumUtils.java
/**
 * Orders Views by their location on-screen.
 * 
 * @param views The views to sort
 * @param yAxisFirst Whether the y-axis should be compared before the x-axis
 * @see ViewLocationComparator
 */

public static void sortViewsByLocationOnScreen(List<? extends View> views, boolean yAxisFirst) {
	Collections.sort(views, new ViewLocationComparator(yAxisFirst));
}