Search code examples
javaandroidlistviewarraylistandroid-arrayadapter

get arrayList value into ArrayAdapter for a listView in android studio


I am trying to put one piece of value in an ArrayList to my listView, below are the details.

Here is the sample of the ArrayList info:

private static final ArrayList<User> users = new ArrayList<User>(){{
        add(new User("Nevin Hobden",38,"Male","Friend","New Mexico","NM"));
        add(new User("Stillman Macken",32,"Male","Friend","Arizona","AZ"));
        add(new User("Stevy Ranscomb",36,"Male","Friend","Arizona","AZ"));
        add(new User("Lynelle Garstang",22,"Female","Family","California","NE"));

I want to grab the state data out from users ArrayList, eg. I only wish to get "New Mexico", "Arizona", "Arizona", and "California" data out to show it on my listView

if that is possible I also want to remove the duplicate and sort in ascending order

   Arizona
   California
   New Mexico

Below is the code I had

   ListView stateListView;
   ArrayList<DataServices.User> stateList = DataServices.getAllUsers();
   ArrayAdapter<DataServices> arrayListAdapter;

   stateListView = view.findViewById(R.id.stateListView);
   arrayListAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1, stateList);
   stateListView.setAdapter(arrayListAdapter);

I know I should not use stateList in the arrayAdapter however I have no idea how should I change for that part, any help is appreciated. Thanks!


Solution

  • If you want to get a list of the states, you can just loop over the original list and put the state into an ArrayList<String>, like this

    ArrayList<String> states = new ArrayList<>();
    for(DataServices.User user : users) {
        states.add(user.state);
    }
    

    If you only want unique states, you could just use a HashSet there instead. Sets eliminate duplicates.

    HashSet<String> states = new HashSet<>();
    for(User user : users) {
        states.add(user.state);
    }
    
    // then convert it back to a list
    ArrayList<String> unique_states = new ArrayList<>(states);
    

    And if you want it to be sorted, you can use Collections.sort to sort the list

    Collections.sort(unique_states);
    

    If your version of Java supports it, you can also do this in fewer lines with streams, but it accomplishes the same thing

    List<String> statesList = users.stream()
                                   .map(u -> u.state)
                                   .collect(Collectors.toList());
    
    Set<String> statesSet = users.stream()
                                 .map(u -> u.state)
                                 .collect(Collectors.toSet());
    
    // Or in one-line
    List<String> unique_states = users.stream()
                    .map(u -> u.state)
                    .collect(Collectors.toSet())
                    .stream()
                    .sorted()
                    .collect(Collectors.toList());