Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting numeric String interval in java

I'm having an Person class with some Person and there details as there name, age band.
The ageband interval is {"0-5", "6-10", "11-30","31-45", "46-50","50-100", "100-110"};

I'm having a Person class with name , ageBand String interval and it's parameterised constructor, getters, setters.

class Person {
    String name;
    String ageBand; //say it is string "0-50" which i pass in constructor while creating a person.
    //getters
    //setters
}

class TestAgeBand {
    public static void main(String args[]) {
        ArrayList<Person> person = new ArrayList<Person>();

        Person p1 = new Person("Mike1", "0-5");   
        Person p2 = new Person("Mike2", "6-10");
        Person p3 = new Person("Mike3", "11-30");   
        Person p4 = new Person("Mike4", "31-45");   
        Person p5 = new Person("Mike5", "50-100");   
        Person p6 = new Person("Mike6", "46-50"); 
        Person p7 = new Person("Mike7", "100-110");

        person.add(p1);
        //adding all persons to list.
    }
}

Here's what I'm doing with my code to sort the interval. I need to sort persons according to increasing intervals. I'm using Treemap to sort the intervals.

Map<String, Person> ageBandMap = new TreeMap<String, Person>(){
    for(Person p: person) {
        ageBandMap.put(p.ageBand, p.name);
    }
}

When I print interval keyset, I get

Output:

[0-5, 100-110, 11-30, 31-45, 46-50, 50-100, 6-10]

Which I don't need. I need intervals sorted like this:

[0-5, 6-10, 11-30, 31-45, 46-50, 50-100, 100-110]

like image 503
Jabongg Avatar asked Sep 04 '17 11:09

Jabongg


1 Answers

Try splitting the your ageBand string and converting it into an Integer, it will be easier to sort.

person.stream().sorted(Comparator.comparing(element -> Integer.parseInt(element.getAgeBand().split("-")[0])))
            .collect(Collectors.toList());

If you don't want to use Java 8, you can do it with Collections.sort() method.

 Collections.sort(person, new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return Integer.parseInt(o1.getAgeBand().split("-")[0]) - Integer.parseInt(o2.getAgeBand().split("-")[0]);
        }
    });
like image 145
Schidu Luca Avatar answered Sep 29 '22 17:09

Schidu Luca