有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中,如何将两个列表与字段名结合起来?

我有两个列表,即plistbrlistplist有产品表的内容,brlist有品牌表的价格表。我想把这两个列表合并起来,再做一个新的列表。我尝试了以下代码,但它复制了两个列表的最后一行值

比如

listplistproduct1、product2、product3和brlist有product1、product2、product3和相应的价格price1、price2、price3。在我的例子中,结果列表有3行,所有值都是相同的product3--brandname3--price3。帮我克服这个错误

代码:

 Map<String, Object> fields = FastMap.newInstance();
 List<Map<String, Object>> products = FastList.newInstance();

   /* actually plist and brlist has the values and displays all the values i checked */

  iter = plist.iterator();
 while (iter.hasNext())

{
  group = iter.next()

  brlist1.add(brlist.price);


  fields.put("productId",group.productId);
  fields.put("brandName",group.brandName);
  fields.put("price",brlist.price);

 products.add(fields);
}

共 (2) 个答案

  1. # 1 楼答案

    我认为最简单的解决方案是创建一个新对象,存储从plist和brlist中提取的字段。这有点令人困惑,但如果你这样做了,那么你就可以直接列出满足你需求的新对象,而不是创建一个包含第一部分和第二部分的列表。我很难理解你的代码虽然你之前的解释很清楚,但代码变量对我来说没有太多意义

    此外,我将不得不对其进行研究,但出于某种原因,对field调用您的方法似乎有些倒退,尽管我已经有一段时间没有使用maps/Java了

  2. # 2 楼答案

    给你:

    new class Product {
    
    private Long productId;
    private String brandName;
    private Double price;
    
    constructor ...
    getters / setters ...
    
    }
    

    然后在你代码的某个地方

    Map<Long, Product> products = new HashMap<Long, Product>();
    
    // Not really certain what type of map you got here... but regardless
    iter = plist.iterator();
    while (iter.hasNext()) {
    
      // Again, some sort of either object or identifier
      group = iter.next()
    
      Product p = new Product();
      p.setBrandName(group.getBrandName());
      p.setProductId(group.getProductId());
    
      products.put(group.productId(), p);
    
    }
    
    iter = brlist.iterator();
    
    while (iter.hasNext()) {
    
      group = iter.next();
    
      // Let's assume the both brlist and plist have the same amount of products
      // That way we can grab the value from the map and set the price.
      products.get(group.getProductId()).setPrice(group.getPrice());
    
    }