数组・List・Map・TreeSet排序总结

[Q&A] 如何实现一个Comparator

Comparator(比较器)的 3 种实现

数组排序

数组升/降序(重排原数组)

# 基本数据类型
int[] size = {1, 3, 7, 2, 4, 5};
Arrays.sort(size); // [1, 2, 3, 4, 5, 7]
int[] ints = Arrays.stream(size).boxed().sorted((a, b) -> b - a).mapToInt(Integer::intValue).toArray(); // [7, 5, 4, 3, 2, 1]

# 元素为对象才可以使用Comparator,基本数据类型只能使用Arrays.sort
--------------------------------------------------------
# 包装类
Integer[] size1 = {1, 3, 7, 2, 4, 5};
Arrays.sort(size1, Comparator.naturalOrder()); //必须Integer  [1, 2, 3, 4, 5, 7]
Arrays.sort(size1, Comparator.reverseOrder()); //必须Integer [7, 5, 4, 3, 2, 1]

--------------------------------------------------------
# 字符
char[] chars = "bca".toCharArray();
Arrays.sort(chars);   // [a, b, c]
// Arrays.sort(chars, Comparator.reverseOrder()); // 编译不过
# Character[] 不存在
List<Character> sortedChars = IntStream.range(0, chars.length).mapToObj(a->chars[a]).sorted(Comparator.reverseOrder()).toList();   // [c, b, a]

--------------------------------------------------------
# 字符串
String[] strs = {"abc","abe","abd","bc"};
Arrays.sort(strs); // [abc, abd, abe, bc]
Arrays.sort(strs, Comparator.reverseOrder()); // [bc, abe, abd, abc]

二维数组(重排原数组)

# 二维数组存储书本的长和宽,先长度降序,再宽度降序
int[][] books = {{1, 2}, {4, 5}, {3, 7}, {3, 4}};

Arrays.sort(books, (book1, book2) -> {
    if (book1[0] == book2[0]) { 
        return book2[1] - book1[1]; // 长度相等,按宽降序
    } else {
        return book2[0] - book1[0]; // 优先按照长度降序
    }
});

排序后:
[4, 5]
[3, 7]
[3, 4]
[1, 2]

List排序

# 方法1 使用list.sort
list.sort(Comparator<? super E> c) 
list.stream().sorted(Comparator<? super T> comparator);

List<Integer> list223 = Arrays.asList(1, 3, 7, 2, 4, 5);
list223.sort(Comparator.naturalOrder()); //升序(重排原集合) [1, 2, 3, 4, 5, 7]  
list223.sort(Comparator.reverseOrder()); //降序(重排原集合) [7, 5, 4, 3, 2, 1]

--------------------------------------------------------
# 方法2:使用Collections.sort
Collections.sort(List<T> list);                         // 元素本身实现Comparator<?superT>接口且Override了compareTo方法
Collections.sort(studentList, Comparator<? super E> c)) // 元素未实现Comparator<? super T>接口

List<Integer> list223 = Arrays.asList(1, 3, 7, 2, 4, 5);
Collections.reverse(list223);  //[5, 4, 2, 7, 3, 1]

<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
    <scope>compile</scope>
</dependency>

Map排序

注意: (因为排序了所以最后结果必须用LinkedHashMap::new收集)

Map<Integer, Integer> map = new HashMap<>();
map.put(1, 11);
map.put(3, 33);
map.put(2, 22);
map.put(5, 55);
map.put(4, 44);

----------------------------------------------------------------
// stream第1部分
HashMap<Integer, Integer> res = map.entrySet().stream()
----------------------------------------------------------------
// stream第2部分
# 按照Key升序
.sorted((e1, e2) -> e1.getKey() - e2.getKey())
.sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
.sorted(Map.Entry.comparingByKey())

# 按照Key降序
.sorted((e1, e2) -> e2.getKey() - e1.getKey())
.sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
.sorted((Map.Entry.<Integer, Integer>comparingByKey().reversed()))

# 按照Value升序
.sorted((e1, e2) -> e1.getValue() - e2.getValue())
.sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
.sorted(Map.Entry.comparingByValue())

# 按照Value降序
.sorted((e1, e2) -> e2.getValue() - e1.getValue())
.sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
.sorted((Map.Entry.<Integer, Integer>comparingByValue().reversed()))
----------------------------------------------------------------
// stream第3部分
# 收集数据(必须用LinkedHashMap::new收集结果)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
----------------------------------------------------------------
{5=55, 4=44, 3=33, 2=22, 1=11}

参考:Java8 对Map进行排序

TreeSet排序

Java如何使用TreeSet排序

算法题

leetcode1839. 所有元音按顺序排布的最长子字符串

----------------------------------------------------------------------
元音字母的顺序都必须按照字典序升序排布 (也就是说所有的 'a' 都在 'e' 前面,所有的 'e' 都在 'i' 前面,以此类推)
----------------------------------------------------------------------

/
 * leetcode1839. 所有元音按顺序排布的最长子字符串
 * 参考的题解→适合自己的题解
 */
public static int longestBeautifulSubstring(String word) {
    Map<Character, Integer> valueMap = new HashMap();
    valueMap.put('a', 0);
    valueMap.put('e', 1);
    valueMap.put('i', 2);
    valueMap.put('o', 3);
    valueMap.put('u', 4);
    
    char[] chars = word.toCharArray();
    int res = 0;
    
    int start = 0;
    for (int i = 1; i < word.length(); i++) {
        // 'a'开始'u'结束且已保证递增,故可以保证('a' ,'e' ,'i' ,'o' ,'u')都必须 至少 出现一次
        // 按照 字典序 升序排布
        if (chars[start] == 'a' && (valueMap.get(chars[i - 1]) + 1 == valueMap.get(chars[i]) || valueMap.get(chars[i - 1]) == valueMap.get(chars[i]))) {
            if (chars[i] == 'u') {
                res = Math.max(i - start + 1, res);
            }
        } else {
            start = i;
        }
    }
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值