Example usage for java.util Collections sort

List of usage examples for java.util Collections sort

Introduction

In this page you can find the example usage for java.util Collections sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void sort(List<T> list, Comparator<? super T> c) 

Source Link

Document

Sorts the specified list according to the order induced by the specified comparator.

Usage

From source file:com.etsy.arbiter.config.ConfigurationMerger.java

/**
 * Merge multiple configurations together
 *
 * @param configs The list of Config objects to merge
 * @return A Config object representing the merger of all given Configs
 *///from   ww  w . j a  v  a  2  s . c o m
public static Config mergeConfiguration(List<Config> configs) throws ConfigurationException {
    Map<String, List<ActionType>> actions = new HashMap<>();

    for (Config c : configs) {
        for (ActionType a : c.getActionTypes()) {
            String name = a.getName();
            if (!actions.containsKey(name)) {
                actions.put(name, Lists.newArrayList(a));
            } else {
                actions.get(name).add(a);
            }
        }
    }

    List<ActionType> actionTypes = new ArrayList<>();

    for (Map.Entry<String, List<ActionType>> entry : actions.entrySet()) {
        if (entry.getValue().size() == 1) {
            actionTypes.addAll(entry.getValue());
        } else {
            List<ActionType> value = entry.getValue();
            Collections.sort(value, new ActionTypePrecedenceComparator());
            ActionType merged = new ActionType();
            merged.setName(entry.getKey());

            // If the tag or xmlns differs, the configuration is invalid
            if (!areAllValuesEqual(value, new Function<ActionType, String>() {
                @Override
                public String apply(ActionType input) {
                    return input.getTag();
                }
            })) {
                throw new ConfigurationException("Tags do not match for ActionType " + entry.getKey());
            }
            if (!areAllValuesEqual(value, new Function<ActionType, String>() {
                @Override
                public String apply(ActionType input) {
                    return input.getXmlns();
                }
            })) {
                throw new ConfigurationException("xmlns do not match for ActionType " + entry.getKey());
            }

            merged.setTag(value.get(0).getTag());
            merged.setXmlns(value.get(0).getXmlns());
            merged.setProperties(mergeMaps(value, new Function<ActionType, Map<String, String>>() {
                @Override
                public Map<String, String> apply(ActionType input) {
                    return input.getProperties();
                }
            }));
            merged.setDefaultArgs(
                    mergeCollectionMaps(value, new Function<ActionType, Map<String, List<String>>>() {
                        @Override
                        public Map<String, List<String>> apply(ActionType input) {
                            return input.getDefaultArgs();
                        }
                    }));

            actionTypes.add(merged);
        }
    }

    Config mergedConfig = new Config();
    mergedConfig.setKillName(getFirstNonNull(configs, new Function<Config, String>() {
        @Override
        public String apply(Config input) {
            return input.getKillName();
        }
    }));
    mergedConfig.setKillMessage(getFirstNonNull(configs, new Function<Config, String>() {
        @Override
        public String apply(Config input) {
            return input.getKillMessage();
        }
    }));
    mergedConfig.setActionTypes(actionTypes);

    return mergedConfig;
}

From source file:gov.nih.nci.iso21090.hibernate.node.ComplexNode.java

/**
 * @param innerNodes List of inner nodes
 *///  w  w w  .jav  a  2s .  c om
public void setInnerNodes(List<Node> innerNodes) {
    this.innerNodes = innerNodes;
    Collections.sort(innerNodes, new NodeNameComparator());
}

From source file:edu.byu.nlp.util.Counters.java

/**
 * Get the n entries with the largest value based on some comparator. 
 * Used by Counter's argMaxList method. 
 *///from  w  w  w.jav a  2  s. c om
public static <E, V extends Comparable<V>> List<E> argMaxList(Set<Entry<E, V>> entrySet, int topn,
        RandomGenerator rnd) {
    topn = (topn > 0) ? topn : entrySet.size();

    List<Entry<E, V>> entries = Lists.newArrayList(entrySet);
    // shuffle to ensure that ties are broken randomly
    if (rnd != null) {
        Collections.shuffle(entries, new RandomAdaptor(rnd));
    }
    // sort to ensure most voted-for options are at the beginning
    Collections.sort(entries, new Comparator<Entry<E, V>>() {
        @Override
        public int compare(Entry<E, V> o1, Entry<E, V> o2) {
            return (o2.getValue()).compareTo(o1.getValue()); // descending order
        }
    });
    // pull out the top n values
    List<E> vals = Lists.newArrayList();
    for (int i = 0; i < Math.min(topn, entries.size()); i++) {
        vals.add(entries.get(i).getKey());
    }
    return vals;
}

From source file:net.dontdrinkandroot.utils.collections.CollectionUtils.java

public static <T extends Number> double getMean(final Collection<T> collection) {

    final int size = collection.size();

    final List<T> sorted = new ArrayList<T>(collection);
    Collections.sort(sorted, new Comparator<T>() {

        @Override//from   www  . j av  a  2 s.  c  om
        public int compare(final T n1, final T n2) {

            return (int) Math.signum(n2.doubleValue() - n1.doubleValue());
        }
    });

    if (size % 2 == 0) {
        return (sorted.get(size / 2).doubleValue() + sorted.get(size / 2 - 1).doubleValue()) / 2;
    } else {
        return sorted.get(size / 2).doubleValue();
    }
}

From source file:de.micromata.tpsb.doc.parser.ParserResult.java

@Override
public Iterator<FileInfo> iterator() {
    Collections.sort(fileInfos, new Comparator<FileInfo>() {

        @Override//from   w ww.  ja va  2 s.  c o m
        public int compare(FileInfo o1, FileInfo o2) {
            return o1.getClassName().compareTo(o2.getClassName());
        }

    });
    return fileInfos.iterator();
}

From source file:net.sf.click.jquery.examples.services.CustomerService.java

@SuppressWarnings("unchecked")
public List<Customer> getCustomersForPage(int offset, int pageSize, final String sortColumn,
        final boolean ascending) {

    // Ok this implementation is a cheat since all customers are in memory
    List<Customer> customers = StartupListener.CUSTOMERS;

    if (StringUtils.isNotBlank(sortColumn)) {
        Collections.sort(customers, new Comparator() {

            public int compare(Object o1, Object o2) {
                int ascendingSort = ascending ? 1 : -1;
                Comparable v1 = (Comparable) PropertyUtils.getValue(o1, sortColumn);
                Comparable v2 = (Comparable) PropertyUtils.getValue(o2, sortColumn);
                if (v1 == null) {
                    return -1 * ascendingSort;
                } else if (v2 == null) {
                    return 1 * ascendingSort;
                }// w w w. j  ava2 s .co  m
                return v1.compareTo(v2) * ascendingSort;
            }
        });
    }

    return customers.subList(offset, Math.min(offset + pageSize, customers.size()));
}

From source file:de.ingrid.portal.global.UniversalSorter.java

@SuppressWarnings("unchecked")
public Collection sort(List list, String property) {
    //return /*from   ww  w  .  j  av  a 2s .  c om*/
    Collections.sort(list, new GermanLangComparator(property, _lang));
    return list;
}

From source file:com.mac.holdempoker.app.hands.Pair.java

@Override
public void haveCard(Card card) {
    if (insertSize == 7) {
        return;/*from w  w  w.  j a  v a2s.c  om*/
    }
    List<Card> ranked = cards.get(card.getRank());
    if (Objects.isNull(ranked)) {
        ranked = new ArrayList();
        cards.put(card.getRank(), ranked);
    }
    ranked.add(card);
    Collections.sort(ranked, cardComparator());
    insertSize++;
}

From source file:me.StevenLawson.BukkitTelnetClient.BTC_PlayerListDecoder.java

public static final boolean checkForPlayerListMessage(final String message, final List<PlayerInfo> playerList) {
    final Matcher matcher = PLAYER_LIST_MESSAGE.matcher(message);
    if (matcher.find()) {
        final String data = matcher.group(1);
        try {//from  w ww .java  2s.  c om
            playerList.clear();

            final JSONObject json = new JSONObject(data);
            final JSONArrayIterable players = new JSONArrayIterable(json.getJSONArray("players"));
            for (JSONObject player : players) {
                final String name = getStringSafe(player, "name");
                playerList.add(new PlayerInfo(name, getStringSafe(player, "ip"),
                        getStringSafe(player, "displayName"), getStringSafe(player, "uuid"),
                        Boolean.valueOf(getStringSafe(player, "tfm.admin.isAdmin")),
                        Boolean.valueOf(getStringSafe(player, "tfm.admin.isTelnetAdmin")),
                        Boolean.valueOf(getStringSafe(player, "tfm.admin.isSeniorAdmin")),
                        getStringSafe(player, "tfm.playerdata.getTag"),
                        getStringSafe(player, "tfm.essentialsBridge.getNickname")));
            }

            Collections.sort(playerList, PlayerInfo.getComparator());

            return true;
        } catch (JSONException ex) {
        }
    }

    return false;
}

From source file:ChartPanelMaker.java

public static ChartPanel createChart(ArrayList<Voter> voters, ArrayList<Candidate> candidates,
        ArrayList<Candidate> committee, String title) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries comitteeDataset = new XYSeries("Committee");
    for (Candidate c : committee) {
        comitteeDataset.add(c.getX(), c.getY());
    }/*from   w w  w  . j av a2 s . com*/
    dataset.addSeries(comitteeDataset);

    int n = voters.size();
    int m = candidates.size();

    int skipN = n / 150;
    if (skipN < 1) {
        skipN = 1;
    }

    int skipM = m / 150;
    if (skipM < 1) {
        skipM = 1;
    }

    Collections.sort(voters, Election.VoterNameComparator);
    Collections.sort(candidates, Election.CandidateNameComparator);

    XYSeries voterDataset = new XYSeries("Voters");
    for (int i = 0; i < n; i++) {
        Voter v = voters.get(i);
        if (i % skipN == 0) {
            voterDataset.add(v.getX(), v.getY());
        }
    }
    dataset.addSeries(voterDataset);

    XYSeries candidateDataset = new XYSeries("Candidates");
    for (int i = 0; i < m; i++) {
        Candidate c = candidates.get(i);
        if (i % skipM == 0) {
            candidateDataset.add(c.getX(), c.getY());
        }
    }
    dataset.addSeries(candidateDataset);

    Shape committeeShape = ShapeUtilities.createDiamond(5);
    Shape voterShape = ShapeUtilities.createDownTriangle(3);
    Shape candidateShape = ShapeUtilities.createUpTriangle(3);

    Color committeeColor = Color.DARK_GRAY;
    Color voterColor = Color.ORANGE;
    Color candidateColor = Color.LIGHT_GRAY;

    JFreeChart chart = ChartFactory.createScatterPlot(title, "", "", dataset, PlotOrientation.VERTICAL, true,
            true, true);
    XYPlot plot = chart.getXYPlot();
    XYItemRenderer r = plot.getRenderer();
    r.setSeriesShape(0, committeeShape);
    r.setSeriesPaint(0, committeeColor);
    r.setSeriesShape(1, voterShape);
    r.setSeriesPaint(1, voterColor);
    r.setSeriesShape(2, candidateShape);
    r.setSeriesPaint(2, candidateColor);
    ChartPanel chartPanel = new ChartPanel(chart);

    return chartPanel;
}