0

I have the following string array: "0 11", "22 34", "5 14", "22 13"... How do I sort it so that both numbers are in increasing order: "0 11", "5 14", "22 13", "22 34"?

4
  • 3
    I don't understand what you mean. In your example, both numbers are not in increasing order; for instance, 14 comes before 13. Commented Nov 27, 2016 at 12:34
  • 2
    In general, storing two informations in a String is a bad idea. Parse the strings and transform them into objects with two int properties. Commented Nov 27, 2016 at 12:35
  • Your post needs editing for clarity of expression; as it stands, it's not clear what you are asking. Commented Nov 27, 2016 at 12:44
  • do you need something like` "0 11", "5 14", "13 22", "22 34"` ? Commented Nov 27, 2016 at 12:46

3 Answers 3

1

You just need to implement an appropriate Comparator. Like that:

public static void main(String[] args) {
    String [] ar = {"0 11", "22 34", "5 14", "22 13"};

    Arrays.sort(ar, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            String [] value1 = o1.split(" ");
            String [] value2 = o2.split(" ");
            Integer o1First = Integer.valueOf(value1[0]);
            Integer o1Second = Integer.valueOf(value1[1]);
            Integer o2First = Integer.valueOf(value2[0]);
            Integer o2Second = Integer.valueOf(value2[1]);
            if (!o1First.equals(o2First))
                return o1First.compareTo(o2First);
            return o1Second.compareTo(o2Second);

        }
    });

    System.out.println(Arrays.toString(ar));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use Collections.sort(List, Comparator) Try this,

Collections.sort(yourList, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String[] split1 = s1.split(" ");
        String[] split2 = s2.split(" ");

        int n = split1[1].compareTo(split2[1]);

        if (n == 0) {
            return Integer.valueOf(split1[0]).compareTo(
                                  Integer.valueOf(split2[0]));
        }

        return n;
    }
});

Comments

0

A little less verbose:

Arrays.sort(ar, Comparator.comparingInt((String s) -> Integer.parseInt(s.split(" ")[0]))
                    .thenComparingInt((String s) -> Integer.parseInt(s.split(" ")[1])));

Unfortunately Java does not currently have built in support for tuple value types. Otherwise the code could be shorter.

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.