Home > database >  How to filter an array list in java
How to filter an array list in java

Time:04-09

I am working with java inside of android studio. I am needing to filter a list of charities by their category when the radio button is chosen. Example: Click Medical radio button and it gives a list of charities that their category is medical. What is the best way to do this? It would be nice if there is a very compact way to do this, but as long as it works I am fine with that. Below is my code for main activity and my object w/ setters and getters.

Main:

package com.example.charityfinder;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //references to buttons and other controls

    Button submitbtn;
    RadioButton medicalRadio, envirRadio, hserviceRadio, educationRadio, publicaRadio,
            cultureRadio, domesticvRadio, hrightsRadio, homelessRadio, religionRadio, youthRadio;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        readcharitydata();
        filterCharity();


        medicalRadio = findViewById(R.id.medicalRadio);
        envirRadio = findViewById(R.id.envirRadio);
        hserviceRadio = findViewById(R.id.hserviceRadio);
        educationRadio = findViewById(R.id.educationRadio);
        publicaRadio = findViewById(R.id.publicaRadio);
        cultureRadio = findViewById(R.id.cultureRadio);
        domesticvRadio = findViewById(R.id.domesticvRadio);
        hrightsRadio = findViewById(R.id.hrightsRadio);
        homelessRadio = findViewById(R.id.homelessRadio);
        religionRadio = findViewById(R.id.religionRadio);
        youthRadio = findViewById(R.id.youthRadio);
        submitbtn = findViewById(R.id.submitbtn);
        submitbtn.setOnClickListener(new View.OnClickListener() {
            String category;
            @Override
            public void onClick(View view) {

                if (medicalRadio.isChecked()) {
                    category = "Medical";
                } else if (envirRadio.isChecked()) {
                    category = "Environmental_Animal";
                } else if (hserviceRadio.isChecked()) {
                    category = "Human_Services";
                } else if (educationRadio.isChecked()) {
                    category = "Education";
                } else if (publicaRadio.isChecked()) {
                    category = "Public_Affairs";
                } else if (cultureRadio.isChecked()) {
                    category = "Culture_Arts_Humanities";
                } else if (domesticvRadio.isChecked()) {
                    category = "Domestic_Violence";
                } else if (hrightsRadio.isChecked()) {
                    category = "Human_Rights";
                } else if (homelessRadio.isChecked()) {
                    category = "Homelessness";
                } else if (religionRadio.isChecked()) {
                    category = "Religious";
                } else if (youthRadio.isChecked()) {
                    category = "Youth";
                }

                filterCharity(category);
            }

        });

    }

    private List<NationalCharity> charities = new ArrayList<>();

    private void readcharitydata() {
        InputStream is = getResources().openRawResource(R.raw.charities);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

        String line = "";
        try {
            //ignore headers
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                //split by comma
                String[] token = line.split(",");
                //Read data
                NationalCharity charity = new NationalCharity();
                charity.setCharity_name(token[0]);
                charity.setCategory(token[1]);
                charity.setWeb_address(token[2]);
                charity.setAddress(token[3]);
                charity.setCity(token[4]);
                charity.setState(token[5]);
                charity.setZipcode(token[6]);
                charity.setMission_statement(token[7]);
                charities.add(charity);

                Log.d("Debug", "Just created: "   charity);
            }
        } catch (IOException e) {
            Log.wtf("Error", "Error reading data file"   line, e);
            e.printStackTrace();
        }

    }

    //needing to filter here from the charities list
    private void filterCharity(String type) {
        if(type.equals("Medical")) {}
        else if(type.equals("Environmental_Animal")) {}
        else if(type.equals("Human_Services")) {}
        else if(type.equals("Education")) {}
        else if(type.equals("Public_Affairs")) {}
        else if(type.equals("Culture_Arts_Humanities")) {}
        else if(type.equals("Domestic_Violence")) {}
        else if(type.equals("Human_Rights")) {}
        else if(type.equals("Homelessness")) {}
        else if(type.equals("Religious")) {}
        else if(type.equals("Youth")) {}


    }

     /*Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
        intent.putExtra("Category", results);
        Log.d("DEBUG: ", results);
        startActivity(intent);*/
}

Object:

package com.example.charityfinder;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import org.bson.types.ObjectId;


public class NationalCharity extends RealmObject {
    @PrimaryKey
    private ObjectId _id;

    private String Address;

    private String Category;

    private String Charity_name;

    private String City;

    private String Mission_statement;

    private String State;

    private String Web_address;

    private String Zipcode;

    public NationalCharity() {}

    // Standard getters & setters
    public ObjectId get_id() { return _id; }
    public void set_id(ObjectId _id) { this._id = _id; }

    public String getAddress() { return Address; }
    public void setAddress(String Address) { this.Address = Address; }

    public String getCategory() { return Category; }
    public void setCategory(String Category) { this.Category = Category; }

    public String getCharity_name() { return Charity_name; }
    public void setCharity_name(String Charity_name) { this.Charity_name = Charity_name; }

    public String getCity() { return City; }
    public void setCity(String City) { this.City = City; }

    public String getMission_statement() { return Mission_statement; }
    public void setMission_statement(String Mission_statement) { this.Mission_statement = Mission_statement; }

    public String getState() { return State; }
    public void setState(String State) { this.State = State; }

    public String getWeb_address() { return Web_address; }
    public void setWeb_address(String Web_address) { this.Web_address = Web_address; }

    public String getZipcode() { return Zipcode; }
    public void setZipcode(String Zipcode) { this.Zipcode = Zipcode; }

    @Override
    public String toString() {
        return "Charity name: "   getCharity_name()   " "   "Category: "   getCategory()   "\n"  
                "Address: "   getAddress()   " "   "City: "   getCity()   " "   "State: "   getState()   " "  
                "Zip code: "   getZipcode()   "\n"   "Mission Statement: "   getMission_statement()   "\n"  
                "Web Address: "   getWeb_address()   "\n";
    }
}

CodePudding user response:

You can use Stream.filter():

charities.stream().filter(c -> type.equals(c.getCharity_name());

CodePudding user response:

You can try this to filter:

 private void filterCharity(String type) {
    List<NationalCharity> filteredList = new ArrayList<>();
    for(NationalCharity charityData : charities)
        if(charityData.getCharity_name().equalsIgnoreCase(type)) 
            filteredList.add(charityData);
    // you have the filtered list "filteredList". Use it however you want
 }
  • Related