Oreo
Oreo

Reputation: 2594

TreeSet Customization in Android Java

I am TreeSet<> to get unique values from an ArrayList, and founded all the unique values, but getting like this:

[Cars, Bikes]

I tried in this way:

Set<String> uniqueCategories; // declared globally

Checkout checkOut;
String strCategories = null;

.......

public void getDataFromDatabase() {

    ArrayList<Checkout> detailArrayListFromDB = serviceDatabase.getCheckOut();
    uniqueCategories = new TreeSet<>();

    for (int i = 0; i < detailArrayListFromDB.size(); i++) {

        String strCategory = detailArrayListFromDB.get(i).getCategory();

        checkOut = new Checkout();
        checkOut.setCategory(strCategory);         
        checkOutArrayList.add(checkOut);    

        uniqueCategories.add(checkOut.getCategory());       
    }

    // name of unique categories
    strCategories = uniqueCategories.toString();
    System.out.println(strCategories);
    Log.d("categories:", strCategories);        
}

But I want to get it like this: Cars, Bikes

And one more thing, How can i show above Strings like this:

Cars

Bikes  

Upvotes: 0

Views: 88

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65821

You can write your own toString.

class MyTreeSet extends TreeSet<String> {

    public String toString() {
        StringBuilder asString = new StringBuilder();
        for (String s : this) {
            if (asString.length() > 0) {
                asString.append("\n");
            }
            asString.append(s);
        }
        return asString.toString();
    }
}

Upvotes: 2

Related Questions