在Java中对字符串编号进行排序的集合 [英] Sorting set of string numbers in java

查看:723
本文介绍了在Java中对字符串编号进行排序的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对保存数字的字符串集进行排序.Ex: [15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8].我需要将其排序为[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].但是,当我使用其中设置了keyList的Collections.sort(keyList);时,获得的结果是[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9].请帮忙.

I need to sort a Set of String's which holds number.Ex: [15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8]. I need to sort it to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]. But when i use Collections.sort(keyList); where keyList is Set, the reult i obtained is [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]. Please help.

推荐答案

编写一个自定义比较器,并将其解析为Collections.sort(Collection,Comparator)的参数.一种解决方案是将您的字符串解析为整数.

Write a custom comparator and parse it as argument to Collections.sort(Collection,Comparator). One solution is parsing your Strings to Integers.

    Collections.sort(keyList, new Comparator<String>()
    {
        @Override
        public int compare(String s1, String s2)
        {
            Integer val1 = Integer.parseInt(s1);
            Integer val2 = Integer.parseInt(s2);
            return val1.compareTo(val2);
        }
    });

这篇关于在Java中对字符串编号进行排序的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆