Map on Filter Giving Compilation Issue

Map on Filter Giving Compilation Issue

What could be the issue here ?
I get the following error on compilation:

error: cannot find symbol
                                .collect(toList())
                                         ^
  symbol:   method toList()
  location: class stocks
 error: invalid method reference
                                .map(Stock::getSymbol)
                                     ^
  cannot find symbol
    symbol:   method getSymbol()
    location: class Stock 

Class Stock does have a public method getSymbol

   static class StockUtil{

            public static Predicate<Stock> isLessThanLimit(Double limit){
                return s -> s.tick < limit;
            }

            public static String toUpperCase(String stock){
                return stock.toUpperCase();
            }
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            List<Stock> stocks = new ArrayList<>(Arrays.asList(new Stock("AMZ",312.0),
                new Stock("Yahoo",212.0),
                new Stock("ORCL",512.0),
                new Stock("SAP",112.0),
                new Stock("Google",412.0),
                new Stock("FB",12.0),
                new Stock("TWT",315.0)));


            //print list of stock names below 400 in uppercase
            System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
                    .map(Stock::getSymbol)
                    .map(StockUtil::toUpperCase)
                    .collect(toList())
                    );
2

2 Answers

Either make sure you use the complete reference to the method as

Collectors.toList()

or import statically

import static java.util.stream.Collectors.toList;

along with a Stock class somewhat as :

class Stock {
    String symbol;
    ...
    public String getSymbol() {...} //getter for symbol
    ...
}

Ideone it!

3

You have not defined the method toList() or you forgot to do static import, try:

import static java.util.stream.Collectors.toList;

no other changes expected in your code.

If you do not want to do static import:

System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
                    .map(Stock::getSymbol)
                    .map(StockUtil::toUpperCase)
                    .collect(Collectors.toList())
                    );

Refer to java documentation of Collectors for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.