1

I have a class

class User{
   String territory;
   String company;
   String name;
}

I have an arraylist of 'User' . I would like to lookup a User object from the list using the String 'territory+company' . The lookup should be based on Binary search. How could i implement it?

The Collections.binarySearch() needs us to create a dummy User object. I dont want that.

Vivek
  • 341
  • 1
  • 5
  • 15

1 Answers1

0

All you need is to implement the Comparable interface for your User class. Then you can use Collections.binarySearch() method (only if your list is sorted of course).

Something like that would work for you:

    public static void main(String[] args) {
        List <User> list = new ArrayList<>();
        list.add(new User("A1", "B1", "Name1"));
        list.add(new User("A2", "B2", "Name2"));
        list.add(new User("A3", "B3", "Name3"));
        list.add(new User("A4", "B4", "Name4"));
        list.add(new User("A5", "B5", "Name5"));

        System.out.println(list.get(Collections.binarySearch(list, new User("A4", "B4", "Name4"))));
    }


    static class User implements Comparable <User>{
        String territory;
        String company;
        String name;

        public User(String territory, String company, String name) {
            this.territory = territory;
            this.company = company;
            this.name = name;
        }

        @Override
        public int compareTo(User o) {
            return (territory+company).compareTo(o.territory+o.company);
        }

        @Override
        public String toString(){
            return territory + "," + company + "," + name;
        }
    }
Grisha Weintraub
  • 7,803
  • 1
  • 25
  • 45
  • 1
    The OP was made more complete: "The Collections.binarySearch() needs us to create a dummy User object. I dont want that.". So this one no longer answers the question. – Petr Bodnár May 11 '20 at 11:42
  • Did you got the answer. I also need the same. – Skand kumar Jul 27 '21 at 18:34
  • the question explicitly asks for not having to create a dummy User object But your answer creates it, you are not really answer this case – Salva Feb 06 '23 at 01:59