Java Code Examples for java.util.Collections#sort()

The following examples show how to use java.util.Collections#sort() . 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: TestUtil.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 2
Source File: LandlordUtil.java    From landlord_client with Apache License 2.0 6 votes vote down vote up
/**
 *判断串联三代二,二必须是对子。是就返回牌面,不是就返回-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;
}
 
Example 3
Source File: AmazonS3Service.java    From Doradus with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 4
Source File: MtuHelper.java    From HttpInfo with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 5
Source File: DataSetApprovalFrequencyComparatorTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 ) );
}
 
Example 6
Source File: AbstractNBTCommand.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: Node.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
	}
}
 
Example 8
Source File: PersistentHashtable.java    From ache with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 9
Source File: AutoRebalanceStrategy.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
      }
    }
  }
}
 
Example 10
Source File: ReplaceCard.java    From DominionSim with MIT License 5 votes vote down vote up
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();
       }
   }
 }
 
Example 11
Source File: BinaryOperationSuffixExpressionParser.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 12
Source File: BasicWorker.java    From jamel with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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;
		}
	}
}
 
Example 13
Source File: MaxPropRouter.java    From the-one with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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);
}
 
Example 14
Source File: ActiveAcademicIntervalYears.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
@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;
}
 
Example 15
Source File: SparqlFusekiQueryImpl.java    From SDA with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * 여러개의 값에서 값을 추출
 * @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);
}
 
Example 16
Source File: Rdn.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
void sort() {
    if (entries.size() > 1) {
        Collections.sort(entries);
    }
}
 
Example 17
Source File: JunctionUtils.java    From abra2 with MIT License 4 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: HassUtils.java    From home-assistant-Android with GNU General Public License v3.0 4 votes vote down vote up
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));
}
 
Example 19
Source File: Package.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
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);
}
 
Example 20
Source File: RobotiumUtils.java    From AndroidRipper with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * 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));
}