Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom order to sort Java String phone number? [closed]

I have a list of Java String phone number & I need to sort out them based on their operator like - "013..." and "017..." they are both same operator number.

List<String> phoneNumberList = new ArrayList<String>();
phoneNumberList.add("01313445566");
phoneNumberList.add("01414556677");
phoneNumberList.add("01515667788");
phoneNumberList.add("01616778899");
phoneNumberList.add("01717889900");
phoneNumberList.add("01818990011");
phoneNumberList.add("01919001122");

When I print them, they look like -

01313445566
01414556677
01515667788
01616778899
01717889900
01818990011
01919001122

But I want to print them like this using custom order -

01313445566,
01717889900,

01414556677,
01919001122,

01515667788,

01616778899,

01818990011

How may I create a custom order to sort them as per my requirement?

like image 808
Bizibuild Professional Builder Avatar asked Dec 06 '25 05:12

Bizibuild Professional Builder


1 Answers

Define your preferred order in a map

Map<String,Integer> order = new HashMap<>();
order.put("013", 1);
order.put("017", 2);
order.put("014", 3);
order.put("019", 4);
order.put("015", 5);
order.put("016", 6);
order.put("018", 7);

Then sort using map order value

list.sort(Comparator.comparing( e -> order.get(e.substring(0,3))))

Update: For java 6

    Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String e1, String e2) {
            return order.get(e1.substring(0,3)).compareTo(order.get(e2.substring(0,3)));
        }
    });

Note: It will work if prefix exists in map.

like image 157
Eklavya Avatar answered Dec 08 '25 17:12

Eklavya