代码帮助 - 避免重复代码并重新排列

时间:2017-11-02 05:43:01

标签: methods java-8 code-cleanup

以下代码获取两种产品类别的产品类别列表

private List<Category> setCategory(CategoryContext categoryContext, CategoryWrapper categoryWrapper) {
      List<Category> categoryList = Collections.emptyList();
      if(categoryWrapper.getCategoryType() == Jewellery) {
         List<JewelleryWrapper> Prices = categoryWrapper.getJewelleryPrices();
         if (Prices != null) {
            categoryList = Prices.stream()
                        .filter(Price -> Price.getJPrice() != null)
                        .map(this::makeCategory)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
          }
      } else if (categoryWrapper.getCategoryType() == Cloth ) { 
          List<ClothWrapper> Prices = categoryWrapper.getClothPrices();
          if (Prices != null) {
          categoryList = Prices.stream()
                        .filter(Price -> Price.getCPrice() != null)
                        .map(this::makeCategoryX)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                }
        }

makeCategory方法如下:

private CategoryItem makeCategory(JewelleryWrapper Price) {
        CategoryItem categoryItem = new CategoryItem();
        categoryItem.setId(Price.getJewelleryId());
        categoryItem.setPrice(Price.getJPrice());
        return categoryItem;
    }

其他将如下:

private CategoryItem makeCategoryX(ClothWrapper Price) {
            CategoryItem categoryItem = new CategoryItem();
            categoryItem.setId(Price.getClothId());
            categoryItem.setPrice(Price.getCPrice());
            return categoryItem;
        }

还有两个要添加的类别。但我觉得这些代码有重复。 任何人都可以帮忙!

0 个答案:

没有答案