java ArrayList排序不区分大小写

xiaoxiao2021-02-28  22

最近在做代码勇士codewars的题目,顺便记录一下自己的解决方案。

1.排序类

1.1 不使用预定义比较器

package com.dylan.practice; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 不区分大小写的升序排序List * @author xusucheng * @create 2017-11-23 **/ public class Sorter { public static List<String> sort(List<String> textbooks) { Collections.sort(textbooks, new Comparator<String>(){ public int compare(String s1, String s2) { return s1.toUpperCase().compareTo(s2.toUpperCase()); } }); return textbooks; } public static void main(String[] args) { List<String> unsort = new ArrayList<String>(); for (String s : new String[]{"Algebra", "History", "Geometry", "english"}) { unsort.add(s); } System.out.println(sort(unsort)); } //自定义比较类 /*static class SortCaseNoSensitive implements Comparator<String>{ public int compare(String s1, String s2) { return s1.toUpperCase().compareTo(s2.toUpperCase()); } }*/ }

1.2 使用预定义比较器

import java.util.ArrayList; import java.util.Collections; class Sorter { public static ArrayList<String> sort(ArrayList<String> textbooks) { Collections.sort(textbooks, String.CASE_INSENSITIVE_ORDER); System.out.println(textbooks); return textbooks; } }

2.测试类

/** * @author xusucheng * @create 2017-11-24 **/ import com.dylan.practice.Sorter; 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<String>(); ArrayList<String> strs = new ArrayList<String>(); 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<String>(); ArrayList<String> strs = new ArrayList<String>(); 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<String>(); ArrayList<String> strs = new ArrayList<String>(); 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)); } }

罗汉爷 认证博客专家 java 数据库管理员 全栈工程师 生活不会像你想象的那么好,也不会像你想象的那么糟。人的脆弱和坚强往往超乎了自己的想象,有时候会因为一句话就泪如雨下,而有时候发现自己艰难的走了很远。QQ: 2480035622Email: indexman@126.com网站:http://www.luohanye.com/
转载请注明原文地址: https://www.6miu.com/read-2300167.html

最新回复(0)