Java List Sort sortByLength(List li, String text)

Here you can find the source of sortByLength(List li, String text)

Description

Sorts the supplied list ordering the items closest to the length of the supplied text first, followed by all larger, and then all shorter.

License

Apache License

Parameter

Parameter Description
li a parameter
text a parameter

Declaration

private static void sortByLength(List<String> li, String text) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**/*from  w  w w. jav  a 2  s.c  o m*/
     * Sorts the supplied list ordering the items closest to the length of the supplied text first, followed by all
     * larger, and then all shorter.
     *
     * @param li
     * @param text
     */
    private static void sortByLength(List<String> li, String text) {
        List<String> tmpStr = new ArrayList<>(li);//make a copy to work with
        List<String> equalList = new ArrayList<>();
        List<String> largerList = new ArrayList<>();
        List<String> smallerList = new ArrayList<>();

        li.clear();

        int l = text.length();

        for (String s : tmpStr) {
            if (s.length() == l) {
                equalList.add(s);
            } else if (s.length() > l) {
                largerList.add(s);
            } else {
                smallerList.add(s);
            }
        }

        sortByLength(largerList, true);
        sortByLength(smallerList, true);
        li.addAll(equalList);
        li.addAll(largerList);
        li.addAll(smallerList);
    }

    private static void sortByLength(List<String> li, boolean ascending) {
        if (!ascending) {
            Collections.sort(li, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o2.length() - o1.length();
                }
            });
        } else {
            Collections.sort(li, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.length() - o2.length();
                }
            });
        }
    }
}

Related

  1. sortAndFormat(List stringList)
  2. sortAndReturn(final List list)
  3. sortBy(List> list, final Map orderBy)
  4. sortByByteDeux(List symbolAL, int delimiter)
  5. sortByClosestMatch(final List strings, final String toMatch)
  6. sortByLength(List list, final boolean ascending)
  7. sortByOccurencies(List lsSame)
  8. sorted(List l, Comparator comparator)
  9. sorted(List l, Comparator comparator)