簡體   English   中英

如何對服裝尺碼列表進行排序(例如 4XL、S、2XL)?

[英]How can I sort a list of clothing sizes (e.g. 4XL, S, 2XL)?

我需要您的幫助來跟蹤查詢。 鑒於以下列表:

["2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL"]

我如何對其進行排序以使其按此順序排列?

[“S”、“M”、“L”、“XL”、“2XL”、“3XL”、“4XL”、“5XL”、“6XL”]

請注意,並非所有尺寸都存在。

構建一個比較器,它會根據您想要的順序進行查找:

Comparator<String> sizeOrder = Comparator.comparingInt(desiredOrder::indexOf);

哪里

desiredOrder = Arrays.asList("S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL");

然后:

yourList.sort(sizeOrder);

如果需要,您可以為查找構建一個Map<String, Integer>

Map<String, Integer> lookup =
    IntStream.range(0, desiredOrder.length())
        .boxed()
        .collect(Collectors.toMap(desiredOrder::get, i -> i));

然后做:

Comparator<String> sizeOrder = Comparator.comparing(lookup::get);

我不相信這會比使用List.indexOfList.indexOf ,因為desiredOrder列表太小了。

與所有與性能相關的內容一樣:使用您認為最易讀的; profile 如果您認為這是一個性能瓶頸,那么只有嘗試替代方案。

一般方法將關注大小字符串背后的模式,而不僅僅是容納樣本輸入。 您有一個由SML表示的基本方向和可選的修飾符(除非M )改變幅度。

static Pattern SIZE_PATTERN=Pattern.compile("((\\d+)?X)?[LS]|M", Pattern.CASE_INSENSITIVE);
static int numerical(String size) {
    Matcher m = SIZE_PATTERN.matcher(size);
    if(!m.matches()) throw new IllegalArgumentException(size);
    char c = size.charAt(m.end()-1);
    int n = c == 'S'? -1: c == 'L'? 1: 0;
    if(m.start(1)>=0) n *= 2;
    if(m.start(2)>=0) n *= Integer.parseInt(m.group(2));
    return n;
}

然后,您可以對尺寸列表進行排序,例如

List<String> sizes = Arrays.asList("2XL", "5XL", "M", "S", "6XL", "XS", "3XS", "L", "XL");
sizes.sort(Comparator.comparing(Q48298432::numerical));
System.out.print(sizes.toString());

其中Q48298432應替換為包含numerical方法的類的名稱。

使用可能更有效且當然更清晰的enum路線的替代方法。

// Sizes in sort order.
enum Size {
    SMALL("S"),
    MEDIUM("M"),
    LARGE("L"),
    EXTRA_LARGE("XL"),
    EXTRA2_LARGE("2XL"),
    EXTRA3_LARGE("3XL"),
    EXTRA4_LARGE("4XL"),
    EXTRA5_LARGE("5XL"),
    EXTRA6_LARGE("6XL");
    private final String indicator;

    Size(String indicator) {
        this.indicator = indicator;
    }

    static final Map<String,Size> lookup = Arrays.asList(values()).stream()
            .collect(Collectors.toMap(
                    // Key is the indicator.
                    s -> s.indicator,
                    // Value is the size.
                    s-> s));

    public static Size lookup(String s) {
        return lookup.get(s.toUpperCase());
    }

    // Could be improved to handle failed lookups. 
    public static final Comparator<String> sizeOrder = (o1, o2) -> lookup(o1).ordinal() - lookup(o2).ordinal();
}

public void test(String[] args) {
    List<String> test = Arrays.asList("S","6XL", "L");
    Collections.sort(test, Size.sizeOrder);
    System.out.println(test);
}

另一種方式可能是這樣的:

List<String> desiredOrder = Arrays.asList("S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL");
 String [] array = new String[desiredOrder.size()];
   list.forEach(s->{
       if (desiredOrder.indexOf(s) != -1)
             array[desiredOrder.indexOf(s)] = s;
   });

List<String> set= Stream.of(array).filter(Objects::nonNull).collect(Collectors.toList());

或者

Set<Integer> integers = new HashSet<>();
    list.forEach(s -> {
        if (desiredOrder.indexOf(s) != -1) {
            integers.add(desiredOrder.indexOf(s));
        }
    });

    List<String> sortedItems = integers.stream()
                                       .sorted()
                                       .map(i->desiredOrder.get(i))
                                       .collect(Collectors.toList());

這是完成大小排序的基本算法。 該算法的基本思想是將大小的每個部分( numbermodifierunit )分解為相應的區域( [0, 1000)[1000, 1000_000)[1000_000, reset] ),然后使用dir來決定modifier方向。 例如:

class Size {
  public static int sizeToInt(String size) {
    int n = size.length(), unit = size.charAt(n - 1), dir = unit == 'S' ? 1 : -1;
    //use a separate method to parse the number & extra modifier if needed
    int i = 0;
    int number = n > 1&&Character.isDigit(size.charAt(i)) ? size.charAt(i++) : '1';
    int modifier = i + 1 < n ? size.charAt(i) : 0;
        return -1 * (unit * 1000_000 + dir * (modifier * 1000 + number));
  }
}

上面的解決方案僅適用於您的簡單情況,對於復雜情況,您需要解析number & modifier並決定如何對region進行分區。 然后您可以按以下代碼按Comparator對大小進行排序:

Comparator<String> sizeComparator = Comparator.comparingInt(Size::sizeToInt);

List<String> sizes = Arrays.asList(
    "3XL", "2XL", "XL",
    "5L", "2L", "L",
    "5M", "2M", "M",
    "S", "2S", "3S",
    "XS", "2XS", "3XS"
);


sizes.sort(sizeComparator);

System.out.println(sizes);
//                  ^--- [
//                         "3XS", "2XS", "XS",
//                         "3S", "2S", "S",
//                         "M", "2M", "5M",
//                         "L", "2L", "5L",
//                         "XL", "2XL", "3XL"
//                       ]

創建一個包含所有可能大小的 Enum 類,並向其中添加getEnum方法以支持以數字開頭的大小:

public enum SizeEnum
{
    S("S"), M("M"), L("L"), XL("XL"), TWO_XL("2XL"), THREE_XL("3XL"), FOUR_XL("4XL"), FIVE_XL("5XL"), SIX_XL("6XL");

    private String value;

    SizeEnum(String value){
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public static SizeEnum getEnum(String value) {
        return Arrays.stream(values())
                .filter(v -> v.getValue().equalsIgnoreCase(value))
                .findAny()
                .orElseThrow(() -> new IllegalArgumentException());
    }
}

在比較器中使用SizeEnum類:

List<String> sizes = Arrays.asList("2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL");
sizes.sort(Comparator.comparing(v -> SizeEnum.getEnum(v.toUpperCase())));
sizes.stream().forEach(l -> System.out.println(l));
public static void SortSizes(String [] sizes, String [] sortedRadixArr) throws Exception{
    
    //creating an int array with same length as sortedRadixArr
    //Here each index of intRadix array is mapped to the index of sortedRadixArr
    //Eg:           intRadix = [0,0,0,0,0]  ----> ["S","M","L","XL","2XL"]  

    int [] intRadix = new int[sortedRadixArr.length];
    
    for(int i = 0; i < sizes.length; i++){
        boolean  matchFlag = false;
        for(int j=0; j< sortedRadixArr.length; j++){
            if(sizes[i] == sortedRadixArr[j]){
                //Whenever the String is matched with the String of sortedRadixArr array, 
                //increment the value of intRadix array at the equivalent index of sortedRadixArr.
                //This helps us to count number same strings(sizes). like two or more "S". 
                //We can't do that with sortedRadixArr as it is a String array.
                intRadix[j]++;
                matchFlag = true;
                break;
            }
        }
        if(!matchFlag){
            throw new Exception("Invalid size found!");
        }
    }
    int count = 0;
    for(int k = 0; k < intRadix.length; k++){
        //Loop thru intRadix array. It contains count of respective sizes(Strings) at each index. 
        //We will re-write sizes array in sorted order with help of intRadix as below.
        while(intRadix[k] > 0){
            sizes[count++] = sortedRadixArr[k];
            intRadix[k]--;
        }
    }
}

}

這里, sortedRadixArr是基數數組,即具有所有可能值的值:

["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"]

sizes是您要排序的數組:

["2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL"]

它接受重復值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM