有一需求,选中周期后,显示规则
* 周一周二周三,就显示周一至周三,
* 周一周二周三周五,显示“周一至周三、周五”
* 周一周三周五,显示“周一、周三、周五”
public class PairX<F, S> {
public F first;
public S second;
/**
* Constructor for a Pair.
*
* @param first the first object in the Pair
* @param second the second object in the pair
*/
public PairX(F first, S second) {
this.first = first;
this.second = second;
}
}
/**
* 周一周二周三,就显示周一至周三,
* 周一周二周三周五,显示“周一至周三、周五”
* 周一周三周五,显示“周一、周三、周五”
*
* @param tartget
* @param sb
*/
public static void format(List<PairX<Integer, String>> tartget, StringBuilder sb) {
if (tartget == null || sb == null) {
return;
}
int stub = -1;
while (!tartget.isEmpty()) {
PairX<Integer, String> first = tartget.get(0);
Integer end = first.first;
for (int i = 1; i < tartget.size(); i++) {
PairX<Integer, String> sub = tartget.get(i);
end += 1;
if (end == sub.first) {
stub = i;
} else {
break;
}
}
if (stub == -1) {
sb.append(first.second + ",");
tartget.remove(0);
} else {
sb.append(first.second + "至" + tartget.get(stub).second + ",");
if (stub == tartget.size() - 1) {
tartget.clear();
} else {
tartget = new ArrayList<>(tartget.subList(stub + 1, tartget.size()));
}
}
stub = -1;
}
String s = sb.toString();
if (!isEmpty(s)) {
boolean b = s.endsWith(",");
if (b) {
sb.setLength(sb.length() - 1);
}
}
}
//TextUtils.isEmpty(s)是android的 ,源码复制出来
public static boolean isEmpty(@Nullable CharSequence str) {
return str == null || str.length() == 0;
}
//注意target需要是排序后的
public static void main(String[] args) {
String s = "123";
StringBuilder sb = new StringBuilder();
List<PairX<Integer, String>> tartget = new ArrayList();
tartget.add(PairX.create(0, "周一"));
tartget.add(PairX.create(1, "周二"));
tartget.add(PairX.create(2, "周三"));
tartget.add(PairX.create(3, "周四"));
tartget.add(PairX.create(4, "周五"));
tartget.add(PairX.create(5, "周六"));
tartget.add(PairX.create(6, "周日"));
format(tartget, sb);
System.out.println(sb.toString());
tartget = new ArrayList();
sb = new StringBuilder();
tartget.add(PairX.create(0, "周一"));
tartget.add(PairX.create(1, "周二"));
tartget.add(PairX.create(2, "周三"));
tartget.add(PairX.create(3, "周四"));
tartget.add(PairX.create(5, "周六"));
tartget.add(PairX.create(6, "周日"));
format(tartget, sb);
System.out.println(sb.toString());
// ==================符合预期==================
// 周一至周日
// 周一至周四,周六至周日
}
网友评论