题目
帮帮我!杰森找不到他的教科书!这是考试日期的前两天,杰森的教科书都出了问题!帮助他按主题排序一个完整的教科书列表(在java中的ArrayList),这样他就可以在测试之前学习。
排序应不区分大小写
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.ArrayList;
import java.util.Collections;
import java.lang.Math;
public class SortingTest {
@Test
public void basicTest() {
ArrayList<String> sorted = new ArrayList<>();
ArrayList<String> strs = new ArrayList<>();
for(String s : new String[] {"Algebra", "History", "Geometry", "English"})
strs.add(s);
for(String s : new String[] {"Algebra", "English", "Geometry", "History"})
sorted.add(s);
assertEquals(sorted, sorter.sort(strs));
}
@Test
public void capitalizationTest() {
ArrayList<String> sorted = new ArrayList<>();
ArrayList<String> strs = new ArrayList<>();
for(String s : new String[] {"Algebra", "history", "Geometry", "english"})
strs.add(s);
for(String s : new String[] {"Algebra", "english", "Geometry", "history"})
sorted.add(s);
assertEquals(sorted, sorter.sort(strs));
}
@Test
public void symbolsTest() {
ArrayList<String> sorted = new ArrayList<>();
ArrayList<String> strs = new ArrayList<>();
for(String s : new String[] {"Alg#bra", "$istory", "Geom^try", "**English"})
strs.add(s);
for(String s : new String[] {"$istory", "**English", "Alg#bra", "Geom^try"})
sorted.add(s);
assertEquals(sorted, sorter.sort(strs));
}
}
解题
My
import java.util.List;
import java.util.Collections;
class sorter {
public static List<String> sort(List<String> textbooks) {
Collections.sort(textbooks,String.CASE_INSENSITIVE_ORDER);
return textbooks;
}
}
Other
有和我一样使用预定义比较器,也有不使用预定义,如下
import java.util.List;
import java.util.*;
class sorter {
public static List<String> sort(List<String> textbooks) {
Collections.sort(textbooks, new SortIgnoreCase());
return textbooks;
}
public static class SortIgnoreCase implements Comparator<Object> {
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
}
import java.util.List;
import java.util.stream.Collectors;
class sorter {
public static List<String> sort(List<String> textbooks) {
return textbooks.stream()
.sorted((b1, b2) -> b1.toLowerCase().compareToIgnoreCase(b2)).collect(Collectors.toList());
}
}
后记
发现自己的list用的很少,基础写法都不熟。
网友评论