1

I have and array of type Object[], containing integers and strings (single letters).

Object[] myArray = {(String) "U", (String) "U", (int) 2, (String) "X", (int) 4, (String) "U"};

What my question is, is there a simple way to sort this array, firstly by ints before strings and secondly by ints in numerical ascending order and string in alphabetical order? I was looking for something similar to the Arrays.sort method, but i don't think it will be that simple.

Thank you

4
  • 3
    There is no point of having this, just create char array or string array and you can sort it with Arrays.sort. Commented Mar 29, 2015 at 1:31
  • Thanks for the answer! May I ask that you elaborate? I'm fairly new to Java, but from what i gather your suggestion may not work? i.e having ints in a String array (as you suggested) would not work? @libik Commented Mar 29, 2015 at 1:39
  • 6
    @user3636636 Having a sequence of heterogeneous types often indicates of a design issue. Commented Mar 29, 2015 at 1:41
  • Why do you cast String literals to String and integer literals to int? Commented Mar 29, 2015 at 1:55

4 Answers 4

2

One way would be to provide a Comparator<Object> instance and check the type of the objects to determine their sorting:

Arrays.sort(myArray, new IntStringComparator());

//...

public static class IntStringComparator implements Comparator<Object> {

    @Override
    public int compare(Object o1, Object o2) {
        if (o1 == null) {
            return -1; // o1 is null, should be less than any value 
        }
        if(o2 == null){
            return 1; // o2 is null, should be less than any non-null value
        }
        if (o1 instanceof Integer) {
            if (o2 instanceof Integer) {
                return Integer.compare((int) o1, (int) o2); // Compare by int
            } else {
                return -1; // int < String
            }
        } else {
            if (o2 instanceof String) {
                return ((String) o1).compareTo((String) o2); // Compare by string
            } else {
                return 1; // String > int
            }
        }
    }
}

Outputs:

[2, 4, U, U, U, X]
Sign up to request clarification or add additional context in comments.

Comments

1

In Java 8:

    Object[] myArray = {(String) "U", (String) "U", (int) 2, (String) "X", (int) 4, (String) "U"};
    Stream.of(myArray).filter(x -> !(x instanceof String))
            .sorted().forEach(System.out::print);
    Stream.of(myArray).filter(x -> x instanceof String)
                        .sorted().forEach(System.out::print);

For David Wallace: in case you want to save the sorted array (I save it to List in this example but it can be converted into .toArray() if you want):

    Object[] myArray = {(String) "U", (String) "U", (int) 2, (String) "X", (int) 4, (String) "U"};
    List<Object> newList = Stream.of(myArray).filter(x -> x instanceof String)
                        .sorted().collect(Collectors.toList());
    Collections.addAll(newList, Stream.of(myArray).filter(x -> !(x instanceof String))
            .sorted().toArray());

    for (Object o : newList) {
        System.out.print(o);
    }

OUTPUT (of both code snippets):

24UUUX

That said, it's a bad practice to mix different types in the same array (to use Object like you did). Different types should be "mixed" only if they have an interface in common (or, if one of them extends the other )!

6 Comments

The OP requested ints before Strings in the output.
Thank you for the answer! very helpful. May you suggest a better data structure to hold the given ints and strings, given that what i have done is bad practice? Thank you @alfasin
@user3636636 well.. the point is not to offer a different data-structure, the point is that different types should not be mixed! If there is a common meaning, there should be an object that wraps them and reflects this property. But since I don't know what was the intention behind this exercise - I can't find a common property that ints and strings share.
Nice usage of Streams. Ironically, they almost make static typing seem meaningless here!
This isn't actually sorting the array is it? You never ended up with an array that had the numbers then the letters, sorted in that order.
|
0

You can specify the function to use to compare objects, and so make it behave however you like. For an example, see Java - How can I most-efficiently sort an array of SomeClass objects by a String field in those objects?

Comments

0

I think the best way to go is to create a Generic Class which will implement the Comparable interface. Such that you can store any type in a Array and having a compare method to do what ever you want.

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.