将星期几列表转换为带连字符的字符串

时间:2014-12-03 20:44:32

标签: java arrays

我是否使用现有的库将周数列表转换为带连字符/连字的字符串?

例如:

["Monday", "Tuesday", "Wednesday", "Friday"]将成为"Monday - Wednesday, Friday"

该列表将始终包含唯一的日期。因此,您永远不会看到["Monday", "Monday", "Tuesday", ...]

谢谢!


感谢kamoor1982's solution below

我必须对他的代码进行一些更改才能处理边缘情况:

enum DayEnum {
    Monday(1),
    Tuesday(2),
    Wednesday(3),
    Thursday(4),
    Friday(5),
    Saturday(6),
    Sunday(7);

    private int value;

    DayEnum(int x) {
        this.value = x;
    }

    public int getValue() {
        return value;
    }
}
...
public static String concatenateDays(List<String> days) {

    // Null check
    if (days == null || days.isEmpty()) {
        return "";
    }

    // Sort list according to order it appears in calendar with Monday as starting day
    Collections.sort(days, new Comparator<String>() {
        @Override
        public int compare(String lhs, String rhs) {
            DayEnum lhsEnum = DayEnum.valueOf(lhs);
            DayEnum rhsEnum = DayEnum.valueOf(rhs);

            return lhsEnum.compareTo(rhsEnum);
        }
    });

    StringBuffer result = new StringBuffer(days.get(0));
    DayEnum valueOf = DayEnum.valueOf(result.toString());
    int previousIndex = valueOf.getValue();
    int length = days.size();

    for (int i = 1; i < days.size(); i++) {
        String day = days.get(i);
        if (previousIndex + 1 == DayEnum.valueOf(day).getValue()) {
            if (i == length - 1 || DayEnum.valueOf(day).getValue() + 1 != DayEnum.valueOf(days.get(i + 1)).getValue()) {
                result.append(" - ");
                result.append(day);
            }
        } else {
            result.append(", ");
            result.append(day);
        }
        previousIndex = DayEnum.valueOf(day).getValue();
    }
    return result.toString();
}

1 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情。

enum DAY {
MONDAY(1), 
TUESDAY(2), 
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7);

private int value;

DAY(int x) {
    this.value = x;
}

public int getValue() {
    return value;
}}

然后使用以下方法进行转换。

public static String concateDays(List<String> days) {

    StringBuffer result = new StringBuffer(days.get(0));
    int previousIndex = DAY.valueOf(days.get(0)).getValue();
    int length = days.size();

    for (int i=1; i< days.size(); i++) {
        String day = days.get(i);
        if(previousIndex + 1 == DAY.valueOf(day).getValue()){
            if(i == length -1 || DAY.valueOf(day).getValue() + 1 != DAY.valueOf(days.get(i+1)).getValue()){
                result.append(" - ");
                result.append(day);
            }
        }else{
            result.append(", ");
            result.append(day);
        }
        previousIndex = DAY.valueOf(day).getValue();
    }
    return result.toString();
}