R
R
Romario212018-05-28 12:56:44
Java
Romario21, 2018-05-28 12:56:44

Java problems with sorting (grouping)?

Hello everyone, I ask for help.
The task is to group users by the number of points:
Ie
ArrayList list = new ArrayList<>();
list.add(new User("Ivanov",2));
list.add(new User("Petrov",2));
list.add(new User("Sidorov",5));
list.add(new User("Pavlov",5));
list.add(new User("Romashkin",1));
The output needs this HashMap:
score: 2 {Ivanov,Petrov}
score: 5 {Sidorov,Pavlov}
score: 1 {Romashkin}
My problem is that only one user is recorded in the HashSet bucket.
Here is my code:

//Изначальный список пользователей
        ArrayList<User> list = new ArrayList<>();
         list.add(new User("Иванов",2));
         list.add(new User("Петров",2));
         list.add(new User("Сидоров",5));
         list.add(new User("Павлов",5));
         list.add(new User("Ромашкин",1));

         //Конечный результат
         HashMap<Integer,HashSet<User>> resultMap = new HashMap<>();

         Iterator iterator = list.iterator();
         while(iterator.hasNext()){
             User item = (User) iterator.next();

     //корзина для пользователей с одинаковым кол-вом очков
             HashSet<User> bucket = new HashSet<>();
              for(int i=0;i<list.size();i++){
                  User subItem = list.get(i);
                  if(item.getLeadQualificated() == subItem.getLeadQualificated()){
                      if(bucket.add(item)){
                         System.out.println("Добавил в корзину : "+item.getLeadQualificated()+"-> "+item.getManager());
                     }

                  }
             }
           
            resultMap.put(item.getLeadQualificated(),bucket);//(key-очки, value - список пользователей с таким кол-вом очков)


         }

   //Выводим resultMap
 Iterator it = resultMap.entrySet().iterator();
         while (it.hasNext()) {
             Map.Entry entry = (Map.Entry)it.next();
             int key = (int) entry.getKey();
            System.out.println("Score: "+key);
             HashSet<User> buketUsers = (HashSet<User>) entry.getValue();
             Iterator<User> it2 = buketUsers.iterator();
             while(it2.hasNext()){
                 User user = it2.next();
                 System.out.println(user.getManager());
             }

             System.out.println("...");

         }

In console:
Added to cart: 5-> Sidorov
Added to cart: 5-> Pavlov
Added to cart: 2-> Ivanov
Added to cart: 2-> Petrov
Added to cart: 1-> Romashkin
_______________________________
Score: 1
Romashkin
.. Score :
2
Petrov
...
Score: 5
Pavlov
...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Eremin, 2018-05-28
@Romario21

Don't suffer, use the streamAPI

ArrayList<User> list = new ArrayList<>();
        list.add(new User("Иванов",2));
        list.add(new User("Петров",2));
        list.add(new User("Сидоров",5));
        list.add(new User("Павлов",5));
        list.add(new User("Ромашкин",1));

        //Конечный результат
        Map<Integer, List<User>> result = list.stream().collect(Collectors.groupingBy(o -> o.scores));

        //выводим результат
        result.forEach((k,v) -> {
            System.out.println("Scores: " + k);
            v.forEach(u -> System.out.println(u.name));
        });

////
Scores 1
Ромашкин
Scores 2
Иванов
Петров
Scores 5
Сидоров
Павлов

I
illuzor, 2018-05-28
@iLLuzor

You create a new Set every time, so there is only one element.
You need to check if such a key already exists, you need to add the user to the existing Set, if not, create a new Set.

V
Vyacheslav, 2018-05-28
@Nirail

The problem is in this piece:

while(iterator.hasNext()){
             User item = (User) iterator.next();

     //корзина для пользователей с одинаковым кол-вом очков
             HashSet<User> bucket = new HashSet<>();
              for(int i=0;i<list.size();i++){
                  User subItem = list.get(i);
                  if(item.getLeadQualificated() == subItem.getLeadQualificated()){
                      if(bucket.add(item)){
                         System.out.println("Добавил в корзину : "+item.getLeadQualificated()+"-> "+item.getManager());
                     }

                  }
             }
           
            resultMap.put(item.getLeadQualificated(),bucket);//(key-очки, value - список пользователей с таким кол-вом очков)
         }

Since you go through all the collections and each time you create a new set, and you add only one element to it (possibly a typo item -> subItem?).
In any case, it is better to rethink the algorithm and make it more optimal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question