如何将这些值分组或合并到java中的单个记录中?

时间:2015-03-19 06:09:50

标签: java arraylist hashmap

我从数据库中检索记录并将其存储在Iterable中。它是'产品'类型。即。,

Iterable<Product> iterable;

 Name        Price   Description    Category
 Samsung     20,000  Its tv          TV
 Sony        15,000  Smart 3d tv     TV
 Moto        19,000   Its android    Mobile
 LG          18,000   Its pc         PC

它包含多行。我需要按“类别”列对这些记录进行分组。如果类别在多个记录中具有相同的值,则需要合并该记录。并且应该添加该行的“价格”列的值以及“描述”也是连接的。我需要在java中做。如何做到java? 我想要的输出是......

  Name            Price      Description                Category
  Samsung, Sony   35,000     Its tv, Smart 3d tv          TV
  Moto            19,000     Its android                Mobile
  LG              18,000     Its pc                       PC

2 个答案:

答案 0 :(得分:0)

你必须做这样的事情......

希望您的Product课程对以下属性有 getter and setters ..

  • 命名
  • <强>递减

    List<String> products = getProducts();/*your List of products*/
    
    HashMap<String, Product> mergedProducts = new HashMap<String, Product>();
    for(Product product : products){
        if(mergedProducts.containsKey(product.getCategory())){
            Product existingProduct = mergedProducts.get(product.getCategory());
    
            String newName = existingProduct.getName() + ", " + product.getName();
            int newPrice = existingProduct.getPrice() + product.getPrice();
            String newDesc = existingProduct.getDesc() + ", " + product.getDesc();
    
            existingProduct.setName(newName);
            existingProduct.setPrice(newPrice);
            existingProduct.setDesc(newDesc);
        } else {
            mergedProducts.put(product.getCategory(), product);
        }
    }
    

答案 1 :(得分:0)

假设你的班级是

class Product{

    private String name;
    private String decription;
    private int price;
    private String category;

 // getters and setters
}

创建另一个类ProductDetail

class ProductDetail{

    private String name;
    private String decription;
    private int totalPrice;
    //  getters and setters
}

Java Logic

    List<Product> productList = getProductList();
    Map<String, ProductDetail> map = new HashMap<String, ProductDetail>();

    for(Product product : productList){

        ProductDetail productDetail = map.get(product.getCategory());

        if(productDetail == null ){
            productDetail = new ProductDetail();
            productDetail.setName(product.getName());
            productDetail.setDecription(product.getDecription());
            productDetail.setTotalPrice(product.getPrice());
            map.put(product.getCategory(), productDetail);
        }else{
            String name = product.getName() + " , " + productDetail.getName();
            String description = product.getDecription() + " , " + productDetail.getDecription();
            int totalPrice = product.getPrice() + productDetail.getTotalPrice();
            productDetail.setDecription(description);
            productDetail.setName(name);
            productDetail.setTotalPrice(totalPrice);
        }
    }