swati
swati

Reputation: 2139

Issue with sorting with collection in java

I have a hashmap:

HashMap<String,QuoteBean> map = new HashMap<String,QuoteBean>();

The QuoteBean is a normal bean:

class QuoteBean{
    String symbol;
    BigDecimal price;
    BigDecimal quoteprice;
    //setter and getter methods
}

Then, I get the values of the map which a collection of QuoteBean objects

Collection obs  =map.values(); //getting all the quoteobjects
List list = new ArrayList(obs); //converted to list

Then to sort:

Collection.sort(list, new SymbolComparator());

SymolComparator is:

public class SymbolComparator implements Comparator<QuoteBean>{
    String symbol;
    @Override
    public int compare(QuoteBean o1, QuoteBean o2) {
        String symbol1=o1.getProductId().getSymbol();
        String symbol2=o2.getProductId().getSymbol();
        return symbol1.compareTo(symbol2);
    }    
}

When I execute the code I get an exeception which says cannot convert String to QuoteBean and the exception throws on the first line.

Upvotes: 0

Views: 145

Answers (3)

Emil
Emil

Reputation: 13789

I think instead of

o1.getProductId().getSymbol();

you should do

o1.getSymbol();

since the QuoteBean has the symbol as a property.

class QuoteBean{
    String symbol;
    BigDecimal price;
    BigDecimal quoteprice;
    //setter and getter methods
}

Upvotes: 0

Jayaram
Jayaram

Reputation: 839

I think the mistake is with these two statements...

String symbol1=o1.getProductId().getSymbol();
String symbol2=o2.getProductId().getSymbol();

if you want to sort the based on string you could just say o1.symbol to get the string. I still don;t understand what getproductid() is used for.

Upvotes: 2

I82Much
I82Much

Reputation: 27326

Are you positive you're not creating a list from the keys?

Collection obs  =map.values(); //getting all the quoteobjects
List list = new ArrayList(obs);

Just for fun make sure you can do

List<QuoteBean> beans = new ArrayList<QuoteBean>(map.values());

Upvotes: 2

Related Questions