Here you can find the source of sortByLength(List
Parameter | Description |
---|---|
li | a parameter |
text | a parameter |
private static void sortByLength(List<String> li, String text)
//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(); } }); } } }