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:by.creepid.docsreporter.context.meta.MetadataFillerChain.java

@PostConstruct
public void init() {
    Collections.sort(fillers, AnnotationAwareOrderComparator.INSTANCE);
}

From source file:de.tor.tribes.util.AllyUtils.java

public static Ally[] getAlliesByFilter(final String pFilter, Comparator<Ally> pComparator) {
    if (pFilter == null) {
        return new Ally[0];
    }// w  w  w .  j  av  a2s  . com
    final String filter = pFilter.toLowerCase();

    List<Ally> allies = new LinkedList<>();
    CollectionUtils.addAll(allies, DataHolder.getSingleton().getAllies().values());

    if (filter.length() > 0) {
        CollectionUtils.filter(allies, new Predicate() {

            @Override
            public boolean evaluate(Object o) {
                return pFilter.length() == 0 || ((Ally) o).getName().toLowerCase().contains(filter)
                        || ((Ally) o).getTag().toLowerCase().contains(filter);
            }
        });
    }

    if (pComparator != null) {
        Collections.sort(allies, pComparator);
    }
    allies.add(0, NoAlly.getSingleton());
    //result = (Ally[]) ArrayUtils.add(result, 0, NoAlly.getSingleton());
    return allies.toArray(new Ally[allies.size()]);
}

From source file:Main.java

public static Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) {

    List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
    if (rawSupportedSizes == null) {
        Log.w(TAG, "Device returned no supported preview sizes; using default");
        Camera.Size defaultSize = parameters.getPreviewSize();
        if (defaultSize == null) {
            throw new IllegalStateException("Parameters contained no preview size!");
        }/*w  w w .ja  v a2 s  .com*/
        return new Point(defaultSize.width, defaultSize.height);
    }

    // Sort by size, descending
    List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(rawSupportedSizes);
    Collections.sort(supportedPreviewSizes, 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 previewSizesString = new StringBuilder();
        for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
            previewSizesString.append(supportedPreviewSize.width).append('x')
                    .append(supportedPreviewSize.height).append(' ');
        }
        Log.i(TAG, "Supported preview sizes: " + previewSizesString);
    }

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

    // Remove sizes that are unsuitable
    Iterator<Camera.Size> it = supportedPreviewSizes.iterator();
    while (it.hasNext()) {
        Camera.Size supportedPreviewSize = it.next();
        int realWidth = supportedPreviewSize.width;
        int realHeight = supportedPreviewSize.height;
        if (realWidth * realHeight < MIN_PREVIEW_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 preview size exactly matching screen size: " + exactPoint);
            return exactPoint;
        }
    }

    // If no exact match, use largest preview 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 (!supportedPreviewSizes.isEmpty()) {
        Camera.Size largestPreview = supportedPreviewSizes.get(0);
        Point largestSize = new Point(largestPreview.width, largestPreview.height);
        Log.i(TAG, "Using largest suitable preview size: " + largestSize);
        return largestSize;
    }

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

From source file:Main.java

/**
 * Returns a three-element array of mutable {@code List}s:
 * <ol>//w ww. ja  va  2  s  .  c o m
 *    </li>
 *      the intersection of {@code a} and {@code b}
 *    <li>
 *    </li>
 *      the {@code a} - {@code b} difference
 *    <li>
 *    </li>
 *      the {@code b} - {@code a} difference
 *    <li>
 * </ol>
 *
 * @param       comparator
 *          a comparator to sort results, or {@code null} to remain
 *          unsorted
 */
public static <T> List<T>[] getIntersectAndDiffs(Collection<? extends T> a, Collection<? extends T> b,
        Comparator<T> comparator) {

    int aSize = a.size();
    List<T> aDiff = new ArrayList<T>(aSize);
    aDiff.addAll(a);

    int bSize = b.size();
    List<T> bDiff = new ArrayList<T>(bSize);
    bDiff.addAll(b);

    if (comparator != null) {
        Collections.sort(aDiff, comparator);
        Collections.sort(bDiff, comparator);
    }

    List<T> abInter = new ArrayList<T>(Math.min(aSize, bSize));

    for (int i = aDiff.size() - 1; i >= 0; i--) {
        T element = aDiff.get(i);

        int index = comparator == null ? bDiff.indexOf(element)
                : Collections.binarySearch(bDiff, element, comparator);

        if (index != -1) {
            bDiff.remove(index);
            aDiff.remove(i);
            abInter.add(element);
        }
    }

    @SuppressWarnings({ "unchecked" })
    List<T>[] array = (List<T>[]) new List[] { abInter, aDiff, bDiff };

    return array;
}

From source file:Main.java

/**
 * Get the list of xml files in the bookmark export folder.
 * @return The list of xml files in the bookmark export folder.
 *///from   w  w  w  .j  a v  a 2s  .  c o  m
public static List<String> getExportedBookmarksFileList() {
    List<String> result = new ArrayList<String>();

    File folder = Environment.getExternalStorageDirectory();

    if (folder != null) {

        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                if ((pathname.isFile()) && (pathname.getPath().toLowerCase(Locale.US).endsWith(".xml")
                        || pathname.getPath().toLowerCase(Locale.US).endsWith(".json"))) {
                    return true;
                }
                return false;
            }
        };

        File[] files = folder.listFiles(filter);

        for (File file : files) {
            result.add(file.getName());
        }
    }

    Collections.sort(result, new Comparator<String>() {

        @Override
        public int compare(String arg0, String arg1) {
            return arg1.compareTo(arg0);
        }
    });

    return result;
}

From source file:Main.java

/**
 * Get the list of xml files in the bookmark export folder.
 * @return The list of xml files in the bookmark export folder.
 *//*from   w ww.jav a  2 s  .c  o m*/
public static List<String> getExportedBookmarksFileList() {
    List<String> result = new ArrayList<String>();

    File folder = getBookmarksExportFolder();

    if (folder != null) {

        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                if ((pathname.isFile()) && (pathname.getPath().endsWith(".xml"))) {
                    return true;
                }
                return false;
            }
        };

        File[] files = folder.listFiles(filter);

        for (File file : files) {
            result.add(file.getName());
        }
    }

    Collections.sort(result, new Comparator<String>() {

        @Override
        public int compare(String arg0, String arg1) {
            return arg1.compareTo(arg0);
        }
    });

    return result;
}

From source file:Main.java

public static Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) {

    List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
    if (rawSupportedSizes == null) {
        //            Log.w(TAG, "Device returned no supported preview sizes; using default");
        Camera.Size defaultSize = parameters.getPreviewSize();
        if (defaultSize == null) {
            throw new IllegalStateException("Parameters contained no preview size!");
        }// w  w w . j  a v a2 s .co m
        return new Point(defaultSize.width, defaultSize.height);
    }

    // Sort by size, descending
    List<Camera.Size> supportedPreviewSizes = new ArrayList<>(rawSupportedSizes);
    Collections.sort(supportedPreviewSizes, 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 previewSizesString = new StringBuilder();
    //            for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
    //                previewSizesString.append(supportedPreviewSize.width).append('x')
    //                        .append(supportedPreviewSize.height).append(' ');
    //            }
    //            Log.i(TAG, "Supported preview sizes: " + previewSizesString);
    //        }

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

    // Remove sizes that are unsuitable
    Iterator<Camera.Size> it = supportedPreviewSizes.iterator();
    while (it.hasNext()) {
        Camera.Size supportedPreviewSize = it.next();
        int realWidth = supportedPreviewSize.width;
        int realHeight = supportedPreviewSize.height;
        if (realWidth * realHeight < MIN_PREVIEW_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 preview size exactly matching screen size: " + exactPoint);
            return exactPoint;
        }
    }

    // If no exact match, use largest preview 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 (!supportedPreviewSizes.isEmpty()) {
        Camera.Size largestPreview = supportedPreviewSizes.get(0);
        Point largestSize = new Point(largestPreview.width, largestPreview.height);
        //            Log.i(TAG, "Using largest suitable preview size: " + largestSize);
        return largestSize;
    }

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

From source file:Main.java

public static <E, V extends Comparable<? super V>, K> Map<K, V> sortByValueDesc(Map<K, V> map, int limit) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o2.getValue()).compareTo(o1.getValue());
        }/*from  www .  j  a v a2  s. co  m*/
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    int counter = 0;
    for (Map.Entry<K, V> entry : list) {
        if (limit > 0 && counter >= limit) {
            break;
        }
        result.put(entry.getKey(), entry.getValue());
        counter++;
    }
    return result;
}

From source file:com.balieiro.facebook.MyFacebookApp.java

public static void loadFriendsList(Response response) {
    try {//from  ww  w. j  a  va2 s.  c o  m
        GraphObject graphObject = response.getGraphObject();
        JSONObject jsonObject = graphObject.getInnerJSONObject();
        JSONArray array = jsonObject.getJSONArray("data");
        instance.mOrderedFriendList.clear();
        for (int i = 0; i < array.length(); i++) {
            JSONObject friend = array.getJSONObject(i);
            FriendItem friendItem = FriendItem.getInstance(friend);
            if (friendItem != null) {
                instance.mOrderedFriendList.add(friendItem);
            }
        }
        Collections.sort(instance.mOrderedFriendList, instance.new FriendComparator());

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.utils.Util.java

public static List<LabelValueBean> readExistingBuldings(String name, String value)
        throws FenixServiceException {
    List<LabelValueBean> edificios = new ArrayList<LabelValueBean>();

    if (name != null) {
        edificios.add(new LabelValueBean(name, value));
    }//from   ww  w.j a  v  a2 s  .c  om

    final List<InfoBuilding> infoBuildings = ReadBuildings.run();
    Collections.sort(infoBuildings, new BeanComparator("name"));

    for (InfoBuilding infoBuilding : infoBuildings) {
        edificios.add(new LabelValueBean(infoBuilding.getName(), infoBuilding.getName()));
    }

    return edificios;
}