2016-09-03 31 views
0

にそれを保存することができますいくつかのいずれかの助け..このを設定反復処理し、リストにそれを格納するための方法 は、オブジェクトのセットを反復処理し、リスト

。私はnullになっています。

public class CartView { 

    public void getCartProductsDetail(HttpServletRequest request, 
             HttpServletResponse response){ 
     List<Product> productsList=null; 
     try { 
      Map<Long,Integer> cart=SessionManager.getSession(request); 
      Set<Long> products=cart.keySet(); 
      for(long productId: products){ 
       productsList.add(ProductDAO.getProductDetails(productId)); 
      } 
      request.setAttribute("productsList", productsList); 
      RequestDispatcher dispatcher = request 
       .getRequestDispatcher(NavigationFiles.VIEW_CART); 
      dispatcher.forward(request, response); 
     } catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 

} 

ありがとうございました。あなたは、Javaを使用したよう

List<Product> productsList=null; 

:あなたの変数productsListを初期化するのを忘れ

答えて

4

How to iterate this set and store it into a list. I am getting null.

あなたがエラーを取得し、なぜあなたは以下を参照することができますように、あるaddメソッドを呼び出したとき、それはまだnullです

List<Product> productsList = cart.keySet() 
    .stream() 
    .map(ProductDAO::getProductDetails) 
    .collect(Collectors.toList()); 

それとも単にであなたの変数を初期化:8あなたはこれを行うにはStream APIに頼ることができますこのような例:ProductDAO.getProductDetails(long)checked exception、マップ・メソッドはFunctionをサポートしていないので、Stream APIに基づいて現在のコードは動作しませんがスローされます

あなたの方法として:

// Initialize the size of the array list with the size of products 
// as it will be its final size which is faster than using the default 
// constructor 
productsList = new ArrayList<>(products.size()); 

レスポンス更新それはchecked exceptionsを投げます。

あなたはそれを修正するには2つの方法があります:


unchecked exceptionchecked exceptionsをラップし、この新しい例外がスローされます別の方法を作成し、その後、あなたはに提供する機能として、この新しいメソッドを使用することができるようになります方法はmapです。そのような

何か:

public static Product getProductDetailsSilently(long val) { 
    try { 
     return ProductDAO.getProductDetails(val); 
    } catch (Exception e) { 
     throw new IllegalStateException(e); 
    } 
} 

ProductListを作成することを可能にするコードは次のようになります。同じことを行うにはlambda expressionでなく、中

List<Product> productsList = cart.keySet() 
    .stream() 
    .map(ProductDAO::getProductDetailsSilently) 
    .collect(Collectors.toList()); 

または依存していますあなたのmapメソッドは次のようになります:

List<Product> productsList = cart.keySet() 
    .stream() 
    .map(val -> { 
     try { 
      return ProductDAO.getProductDetails(val); 
     } catch (Exception e) { 
      throw new IllegalStateException(e); 
     } 
    }) 
    .collect(Collectors.toList()); 
+0

ありがとうございます。しかし、ストリームは機能していません。 – Anju

+0

ok..thats fine.working better。 – Anju

+0

ストリームが機能していませんか?それの問題は何ですか? –