Java如何以不区分大小写的顺序对数组值进行排序?
默认情况下,对数组进行排序时,值将按区分大小写的顺序排序。本示例说明如何按不区分大小写的顺序对其进行排序。
package org.nhooo.example.util; import java.util.Arrays; public class SortArrayCaseSensitivity { public static void main(String[] args) { String[] teams = new String[5]; teams[0] = "Manchester United"; teams[1] = "chelsea"; teams[2] = "Arsenal"; teams[3] = "liverpool"; teams[4] = "EVERTON"; //排序数组,默认情况下将按区分大小写的顺序排序。 //[阿森纳,埃弗顿,曼联,切尔西,利物浦] Arrays.sort(teams); System.out.println("Case sensitive : " + Arrays.toString(teams)); //以不区分大小写的顺序对数组进行排序 //[阿森纳,切尔西,埃弗顿,利物浦,曼联 Arrays.sort(teams, String.CASE_INSENSITIVE_ORDER); System.out.println("Case insensitive: " + Arrays.toString(teams)); } }
上面的代码片段的结果:
Case sensitive : [Arsenal, EVERTON, Manchester United, chelsea, liverpool] Case insensitive: [Arsenal, chelsea, EVERTON, liverpool, Manchester United]