0

I am just a beginner and learning Java to my own! I just have an arraylist of objects of Users:

class Users{
   public userName;
   public userNumber;
}  

then I create a model as:

 ArrayList<Users> model=new ArrayList<Users>();

and added the model items as:

 model.add(new Users("abc","123"));
 model.add(new Users("def","888"));
 model.add(new Users("abc","246"));
 model.add(new Users("def","999"));
 model.add(new Users("abc","456"));

What I want to do is to print the model in this way that should show similar grouped data with group name as:

 for(int i=0;i:i<users.size;i++){
    System.out.printlin("users:::"+users.get(i).userNumber);
 }

But it should group and print group by name too that is:

 abc ->
       users:::123
       users:::246
       users:::456

 def ->
       users:::888
       users:::999  

So I want to group the data and then print the data in grouped format with each group name also!

How can I do that, I am just learning Java to my own. Thanks in advance

  • you need to use `java.util.Map`, this datastructure holds key-value pair. Your key will be userName and value will be list of userNumber. Then you can have a loop which prints the entries from map. You can also read about java8 stream api. All the best :) – Laxman Sep 16 '19 at 07:05
  • if you want print data only then you can use oveeride method toString in user class . link (https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java) – nikk Sep 16 '19 at 07:19

5 Answers5

0

A quick and easy way to do what you want is to use a HashMap. Hash maps are key-value collections, son in your case, you would create a HashMap<String, List<String>> which stores the username as key, and the userNumber as a list of values (since you have more than 1).

Then your code would change as follows:

  1. Iterate over all the users that your have.
  2. If the username exists in the hashmap, add the usernumber to it.
  3. If the username does not exist, add it to the hashmap with the usernumber as the first element of its list.

Lastly, you would then iterate over the hashmap, printing the key and values which it has.

npinti
  • 51,780
  • 5
  • 72
  • 96
0

Try Something like below using Java Streams.

//group by user name
Map<String, Set<String>> map =
            model.stream().collect(
                    Collectors.groupingBy(Users::getUserName,
                            Collectors.mapping(Users::getUserNumber, Collectors.toSet())
                    )
            );
System.out.println(map);

Make sure to have the getter methods getUserName(), getUserNumber() implemented in Users class. Here i have assumed that both userName and userNumber are string typed data.

Anjana
  • 903
  • 1
  • 5
  • 13
0
public class User {
private String userName;
public String getUserName() {
    return userName;
}

public User(String userName, String userNumber) {
    this.userName = userName;
    this.userNumber = userNumber;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserNumber() {
    return userNumber;
}

public void setUserNumber(String userPassword) {
    this.userNumber = userPassword;
}

private String userNumber;
}

MainClass

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainMethod {

private static HashMap<User, ArrayList<User>> maps;
private static ArrayList<User> user1list;
private static ArrayList<User> user2list;

public static void main(String...args) {
    maps = new HashMap<>();
    user1list = new ArrayList<>();
    user2list = new ArrayList<>();
    User user1 = new User("Ram", "1234");
    User user2 = new User("Alish", "5678");
    User user3 = new User("Ram", "91011");
    User user4 = new User("Alish", "121314");
    user1list.add(user1);
    user1list.add(user3);
    user2list.add(user2);
    user2list.add(user4);
    maps.put(user1, user1list );
    maps.put(user2, user2list);

   /// User one lists
    for ( User userone: maps.get(user1)) {
        System.out.println("userone Name:::"+userone.getUserName());
        System.out.println("User one Number:::"+userone.getUserNumber());
    }

    System.out.println();
     // USer tow list
    for (User usertwo: maps.get(user2)) {
        System.out.println("User two Name:::" +usertwo.getUserName());
        System.out.println("User two Number :::" +usertwo.getUserNumber());
    }
  }
 }
0

please try the code below -

public class Users {

public String userName;
public String userNumber;

public Users(String userName, String userNumber) {
    this.userName = userName;
    this.userNumber = userNumber;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserNumber() {
    return userNumber;
}

public void setUserNumber(String userNumber) {
    this.userNumber = userNumber;
}

public static void main(String ar[]) {

    ArrayList<Users> model = new ArrayList<Users>();
    model.add(new Users("abc", "123"));
    model.add(new Users("def", "888"));
    model.add(new Users("abc", "246"));
    model.add(new Users("def", "999"));
    model.add(new Users("abc", "456"));

    Map<String, Set<String>> map = model.stream().collect(Collectors.groupingBy(Users::getUserName,
            Collectors.mapping(Users::getUserNumber, Collectors.toSet())));
    for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
        Set set = entry.getValue();
        Iterator value = set.iterator();
        while (value.hasNext()) {
            System.out.println(entry.getKey() + " : " + value.next());
        }
    }

}

}

Bheem Singh
  • 607
  • 7
  • 13
0
Map<String, List<Users>> use = model.stream.collect(Collectors.groupinBy(Person::getUsername)) ;

You use this approach to print the data by group

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
ak_bhai
  • 41
  • 2