1

I have a column VALUE in my table that contains:

`M_SYSCONFIG = 200600,2600000,700000600,110000600,150000600`

When I sort this list the result is: 110000600,150000600,110000600,200600,2600000,700000600

However, I need the list to be sorted as follows (treat the strings as integers): 200600,2600000,110000600,150000600,700000600

This is the code I have right now for sorting the list:

    JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);

    for (int i = 0; i< jsArray.size(); i++) {
        JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
        String trasactionType = JSON.get(js, "CODE");
        String value = JSON.get(js, "VALUE");
        List<String> data = Arrays.asList(value.split(","));
        Collections.sort(data);

I need to obtain the results as strings because after sorting I want to apply the following code:

        StringBuilder sbValue = new StringBuilder();
        if(ft_other_cn.equals(trasactionType)) {
            long limitOtherCimb = limit.getFtOtherCimbLimit();
            sbValue.append(limitOtherCimb).append(",");
            for(String values:data) {
                Long limitSysConfig = null;
                try {
                    limitSysConfig = Long.parseLong(values);
                } catch (Exception e) {}
                if(limitSysConfig == null) {
                    continue;
                }
                if(limitSysConfig > limitOtherCimb) {
                    continue;
                }
                sbValue.append(limitSysConfig).append(",");
            }
            customerLimit.setFtOtherCnLimit(StringUtils.removeEnd(sbValue.toString(), ","));
4
  • Hint: Convert the values to numbers. Commented May 23, 2018 at 7:08
  • So you want to sort as numeric values not Strings Commented May 23, 2018 at 7:08
  • Instead of having list of strings create list of numerical types (possibly Long or even BigInteger depending on how big your numbers are). Then sorting it should be easier. Commented May 23, 2018 at 7:09
  • Of-topic : You read the DB and directly get a JSON, then work on the JSON to create a sorted list ? Why the JSON ? Commented May 23, 2018 at 7:17

6 Answers 6

3

You need to convert you string values to integers like this and then need to sort.

JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
    String trasactionType = JSON.get(js, "CODE");
    String value = JSON.get(js, "VALUE");
    List<String> data = Arrays.asList(value.split(","));
    List<Integer> intList = new ArrayList<Integer>();
    for(String s : data){
        intList.add(Integer.valueOf(s));
    }
    Collections.sort(intList);
Sign up to request clarification or add additional context in comments.

4 Comments

i need String result, because i want to concat after that sorting.
@YeruAdi after sorting you can again convert to string values
can you help me dude ? i try to convert but i can't
can you help me dude ? i try to convert but i can't @Muddassir Rahman
2

I suggest using biginteger because your numbers seems quite large. It's not the most efficient and optimized solution but yeah it will work

public static List<String> sortData(List<String> data){
            List<BigInteger>convertedData=new ArrayList<BigInteger>();
        for (String s : data) 
        {
            //System.out.println(s);
         convertedData.add(new BigInteger(s));
        }
        Collections.sort(convertedData);
        List<String>sortedData=new ArrayList<String>();

        for (BigInteger b : convertedData) 
        {
            sortedData.add(String.valueOf(b));

        }
        return sortedData;
    }

Your code:

JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);

for (int i = 0; i< jsArray.size(); i++) {
    JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
    String trasactionType = JSON.get(js, "CODE");
    String value = JSON.get(js, "VALUE");
    List<String> data = Arrays.asList(value.split(","));
    List<String> sortedData=sortData(data);  **<------**

Comments

1

Implement a Comparator like this:

Collections.sort(data, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return new Long(Long.parseLong(o1)).compareTo(Long.parseLong(o2));
            }
        });

3 Comments

this sounds rather slow
i am sorry, because i am new here dude :)
That looks to be quite suboptimal. Casting all elements to int/long, comparing them and then casting back to strings would most likely be faster. If I'm correct you're performing about log(n) times more casts.
1

You can take help of streams introduced in java 8.

Just add the below line after creating the List and you would have sorted string list

List<String> data = Arrays.asList(value.split(","));

data=data.stream().mapToLong(Long::parseLong).sorted().mapToObj(String::valueOf).collect(Collectors.toList());

If you very large numbers you can use BigInteger

data=data.stream().map(BigInteger :: new ).sorted().map(String::valueOf).collect(Collectors.toList());

If you are using java 6,7 you would have to use a comparator as mentioned by Taher

Collections.sort(data, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return new Long(Long.parseLong(o1)).compareTo(Long.parseLong(o2));
            }
        });

Comments

1

If you are not able to change your list, then the simplest way is to build a comparator using Java 8 and use the string values as bigintegers. You do not need to convert your string list to a number list.

List<String> list = Arrays.asList("200600,2600000,700000600,110000600,150000600".split(","));

list.sort(Comparator.comparing(item -> new BigInteger(item)));

System.out.println(list);

The magic happens within

Comparator.comparing(item -> new BigInteger(item))

With this you are constructing a Comparator (which is needed for sorting), that compares all items converted to BigIntegers.

Comments

0

You are sorting the numbers as Strings - as a string, 11 comes before 2. You need to first convert the array of strings to numbers, then sort them as numbers.

With the Streams API you can do that on one line:

String value = ...;
List<Long> data = Arrays.stream(value.split(",")).map(Long::new).sorted()
                     .collect(Collectors.toList());

Since you need them as Long later, I'm using Long as the numeric type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.