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:Main.java

/**
 * Finds the most optimal size. The optimal size is when possible the same as
 * the camera resolution, if not is is it the best size between the camera solution and
 * MIN_SIZE_PIXELS/*from   w w w  .  java2 s  . c  om*/
 * @param screenResolution
 * @param rawSupportedSizes
 *@param defaultCameraSize @return optimal preview size
 */
private static Point findBestSizeValue(Point screenResolution, List<Camera.Size> rawSupportedSizes,
        Camera.Size defaultCameraSize) {

    if (rawSupportedSizes == null) {
        Log.w(TAG, "Device returned no supported sizes; using default");
        if (defaultCameraSize == null) {
            throw new IllegalStateException("Parameters contained no size!");
        }
        return new Point(defaultCameraSize.width, defaultCameraSize.height);
    }

    // Sort by size, descending
    List<Camera.Size> supportedSizes = new ArrayList<>(rawSupportedSizes);
    Collections.sort(supportedSizes, new Comparator<Camera.Size>() {
        @Override
        public int compare(Camera.Size a, Camera.Size b) {
            int aPixels = a.height * a.width;
            int bPixels = b.height * b.width;
            if (bPixels > aPixels) {
                return -1;
            }
            if (bPixels < aPixels) {
                return 1;
            }
            return 0;
        }
    });

    if (Log.isLoggable(TAG, Log.INFO)) {
        StringBuilder sizesString = new StringBuilder();
        for (Camera.Size supportedSize : supportedSizes) {
            sizesString.append(supportedSize.width).append('x').append(supportedSize.height).append(' ');
        }
        Log.i(TAG, "Supported sizes: " + sizesString);
    }

    double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;

    // Remove sizes that are unsuitable
    Iterator<Camera.Size> it = supportedSizes.iterator();
    while (it.hasNext()) {
        Camera.Size supportedSize = it.next();
        int realWidth = supportedSize.width;
        int realHeight = supportedSize.height;
        if (realWidth * realHeight < MIN_SIZE_PIXELS) {
            it.remove();
            continue;
        }

        boolean isCandidatePortrait = realWidth < realHeight;
        int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
        int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
        double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
        double distortion = Math.abs(aspectRatio - screenAspectRatio);
        if (distortion > MAX_ASPECT_DISTORTION) {
            it.remove();
            continue;
        }

        if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
            Point exactPoint = new Point(realWidth, realHeight);
            Log.i(TAG, "Found size exactly matching screen size: " + exactPoint);
            return exactPoint;
        }
    }

    // If no exact match, use largest size. This was not a great idea on older devices because
    // of the additional computation needed. We're likely to get here on newer Android 4+ devices, where
    // the CPU is much more powerful.
    if (!supportedSizes.isEmpty()) {
        Camera.Size largestCameraSizes = supportedSizes.get(0);
        Point largestSize = new Point(largestCameraSizes.width, largestCameraSizes.height);
        Log.i(TAG, "Using largest suitable size: " + largestSize);
        return largestSize;
    }

    // If there is nothing at all suitable, return current size
    if (defaultCameraSize == null) {
        throw new IllegalStateException("Parameters contained no size!");
    }
    Point defaultSize = new Point(defaultCameraSize.width, defaultCameraSize.height);
    Log.i(TAG, "No suitable sizes, using default: " + defaultSize);

    return defaultSize;
}

From source file:net.sourceforge.eclipsetrader.trading.internal.watchlist.ColumnRegistry.java

public static IConfigurationElement[] getProviders() {
    List list = new ArrayList(map.values());
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
            String s1 = "";
            String s2 = "";
            if (((IConfigurationElement) o1).getAttribute("name") != null)
                s1 = ((IConfigurationElement) o1).getAttribute("name");
            if (((IConfigurationElement) o2).getAttribute("name") != null)
                s2 = ((IConfigurationElement) o2).getAttribute("name");
            return s1.compareTo(s2);
        }/*  w  w w  .  j  a v  a 2s.co  m*/
    });
    return (IConfigurationElement[]) list.toArray(new IConfigurationElement[list.size()]);
}

From source file:utils.HttpComm.java

public static List<ProbePair> multiProbe(List<String> workersList) throws Exception {
    List<ProbePair> results = new LinkedList<>();
    for (String workerURL : workersList)
        results.add(new ProbePair(workerURL, Integer.parseInt(probe(workerURL))));

    Collections.sort(results, new Comparator<ProbePair>() {
        @Override/*from w w w.j av a 2s.  c  o m*/
        public int compare(ProbePair pair1, ProbePair pair2) {
            return pair1.getProbeResult() - pair2.getProbeResult(); // Ascending
        }

    });
    return results;
}

From source file:net.sourceforge.fenixedu.presentationTier.renderers.providers.ExecutionYearsForDegreeCurricularPlanProvider.java

public static List<ExecutionYear> getExecutionYears(HasDegreeCurricularPlan bean) {
    List<ExecutionYear> executionYears = new ArrayList<ExecutionYear>();
    for (ExecutionYear year : Bennu.getInstance().getExecutionYearsSet()) {
        if (year.isInclusivelyBetween(bean.getDegreeCurricularPlan().getInauguralExecutionYear(),
                bean.getDegreeCurricularPlan().getLastExecutionYear())) {
            executionYears.add(year);/*from  w  w  w. j  a  v  a  2  s.c o m*/
        }
    }
    Collections.sort(executionYears, new ReverseComparator());
    return executionYears;
}

From source file:at.meikel.dmrl.webapp.rest.PlayerService.java

@RequestMapping(value = { "/players" }, method = RequestMethod.GET)
@ResponseBody//from www. j a v  a2s.co  m
public List<Player> getAllPlayers() {
    List<Player> result = null;
    if (server != null) {
        result = server.getRankingList().getAllPlayers();
    }

    if (result == null) {
        result = new Vector<Player>();
    }

    Collections.sort(result, new Comparator<Player>() {
        @Override
        public int compare(Player p1, Player p2) {
            if (p1 == null) {
                return p2 == null ? 0 : 1;
            } else {
                if (p2 == null) {
                    return -1;
                } else {
                    return (int) Math.signum(p1.getRanglistenwert() - p2.getRanglistenwert());
                }
            }
        }
    });

    return result;
}

From source file:com.nttec.everychan.chans.chan420.Chan420JsonMapper.java

static List<SimpleBoardModel> mapBoards(JSONObject categories, JSONObject boards) {
    ArrayList<JSONObject> catsArray = new ArrayList<>();
    JSONArray catsJsonArray = categories.getJSONArray("categories");
    for (int i = 0; i < catsJsonArray.length(); ++i)
        catsArray.add(catsJsonArray.getJSONObject(i));
    Collections.sort(catsArray, new OrderComparator());

    ArrayList<JSONObject> boardsArray = new ArrayList<>();
    JSONArray boardsJsonArray = boards.getJSONArray("boards");
    for (int i = 0; i < boardsJsonArray.length(); ++i)
        boardsArray.add(boardsJsonArray.getJSONObject(i));
    Collections.sort(boardsArray, new OrderComparator());

    List<SimpleBoardModel> list = new ArrayList<SimpleBoardModel>();
    for (JSONObject category : catsArray) {
        int catId = category.optInt("id");
        String catName = category.optString("title", "");
        boolean catNsfw = category.optInt("nws_category") == 1;
        for (JSONObject board : boardsArray) {
            if (board.optBoolean("picked"))
                continue;
            if (board.optInt("category") == catId) {
                board.put("picked", true);
                list.add(ChanModels.obtainSimpleBoardModel(Chan420Module.CHAN_NAME, board.getString("board"),
                        StringEscapeUtils.unescapeHtml4(board.getString("title")), catName,
                        (catNsfw || (board.optInt("nws_board") == 1))));
            }/* www.ja  v a  2  s.c om*/
        }
    }
    for (JSONObject board : boardsArray) {
        if (board.optBoolean("picked"))
            continue;
        list.add(ChanModels.obtainSimpleBoardModel(Chan420Module.CHAN_NAME, board.getString("board"),
                StringEscapeUtils.unescapeHtml4(board.getString("title")), "",
                (board.optInt("nws_board") == 1)));
    }
    return list;
}

From source file:com.alibaba.zonda.logger.server.util.DirectoryListener.java

public List<File> list(File startDirectory, String filterRegex) throws IOException {
    List<File> dirList = new ArrayList<File>();
    walk(startDirectory, dirList);//from w  w w .j  a v  a  2s .  c o  m
    Collections.sort(dirList, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return (Long.valueOf(f1.lastModified())).compareTo(Long.valueOf(f2.lastModified()));
        }
    });
    List<File> filteredDirList = new ArrayList<File>();
    for (File f : dirList) {
        if (f.getName().matches(filterRegex)) {
            filteredDirList.add(f);
        }
    }
    return filteredDirList;
}

From source file:au.org.biodiversity.nsl.tree.SimpleProfiler.java

public static void stopProfiling() {
    profiling = false;//from  w  ww.ja va 2  s.c  o m

    stoploggingts = System.currentTimeMillis();
    log.info("logging for " + (stoploggingts - startloggingts) + " ms");

    Map<String, Long> byTime = new HashMap<String, Long>();

    for (String k : itemTime.keySet()) {
        long t = itemTime.get(k);
        int ct = itemCt.get(k);

        //byTime.put(k, (t / ct));
        byTime.put(k, t); // I mainly care about the total time
    }

    ArrayList<Entry<String, Long>> byTimeSorted = new ArrayList<Entry<String, Long>>(byTime.entrySet());
    Collections.sort(byTimeSorted, new Comparator<Entry<String, Long>>() {
        public int compare(Entry<String, Long> o1, Entry<String, Long> o2) {
            return (int) (o1.getValue() - o2.getValue());
        }
    });

    for (Entry<String, Long> kk : byTimeSorted) {
        String k = kk.getKey();
        long t = itemTime.get(k);
        int ct = itemCt.get(k);

        log.info(k + " ct " + ct + " time " + t + " ms is " + (t * 100 / (stoploggingts - startloggingts))
                + "% avg " + (t / ct));

    }
}

From source file:net.panthema.BispanningGame.GraphString.java

public static String write_graph(MyGraph g, Transformer<Integer, Point2D> gl) {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter pw = new PrintWriter(ba);

    // print the vertex list

    pw.print('V');
    pw.print(g.getVertexCount());/*from w  w w  . ja  v a 2 s .com*/
    pw.print(':');

    Collection<Integer> vcoll = g.getVertices();
    ArrayList<Integer> vlist = new ArrayList<Integer>(vcoll);
    Collections.sort(vlist, new Comparator<Integer>() {
        public int compare(Integer arg0, Integer arg1) {
            return arg0 - arg1;
        }
    });

    for (Integer v : vlist) {
        pw.print('i');
        pw.print(v);

        Point2D pos = gl.transform(v);
        pw.print('x');
        pw.print((int) pos.getX());
        pw.print('y');
        pw.print((int) pos.getY());

        pw.print('/');
    }
    pw.print(';');

    // print the edge list

    pw.print('E');
    pw.print(g.getEdgeCount());
    pw.print(':');

    Collection<MyEdge> ecoll = g.getEdges();
    ArrayList<MyEdge> elist = new ArrayList<MyEdge>(ecoll);
    Collections.sort(elist, new Comparator<MyEdge>() {
        public int compare(MyEdge arg0, MyEdge arg1) {
            return arg0.id - arg1.id;
        }
    });

    for (MyEdge e : elist) {
        Integer e_x = g.getEndpoints(e).getFirst();
        Integer e_y = g.getEndpoints(e).getSecond();

        pw.print('i');
        pw.print(e.id);

        pw.print('t');
        pw.print(e_x);
        pw.print('h');
        pw.print(e_y);

        pw.print('c');
        pw.print(e.color);

        pw.print('/');
    }
    pw.print(';');

    pw.flush();

    return ba.toString();
}

From source file:com.sec.ose.osi.util.tools.Tools.java

public static ArrayList<String> sortByValue(final HashMap<String, Integer> map) {
    ArrayList<String> key = new ArrayList<String>();
    key.addAll(map.keySet());/*from w  w w .j a  v a  2  s. c om*/
    Collections.sort(key, new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            Integer v1 = map.get(o1);
            Integer v2 = map.get(o2);
            return v1.compareTo(v2);
        }
    });
    Collections.reverse(key);
    return key;
}