Java 8过滤ListOfMap以检查密钥是否存在,如果存在则收集地图

时间:2019-02-27 04:03:42

标签: java java-8 hashmap java-stream collectors

以下是用于从结果集中收集listofmap并检查特定产品的listofmap的代码,如果存在产品,则获取该映射。 请帮我在java8中做

List<Map<String,Object>>    lmProducts  =   new ArrayList<Map<String, Object>>();
Map<String, Object>         map         =   null;
try {
    if(resultSet.next()){
        System.out.println("PRODUCT\t PRICE\t QUANTITY");
        do{
            map  =   new HashMap<String, Object>();
            map.put("NAME", resultSet.getString("NAME"));
            map.put("PRICE", resultSet.getString("PRICE"));
            map.put("QUANTITY", resultSet.getString("QUANTITY"));
            System.out.println(resultSet.getString("NAME")+"\t "+resultSet.getInt("PRICE")+"\t "+resultSet.getInt("QUANTITY"));
            lmProducts.add(map);
        }while (resultSet.next());
    }

}catch (SQLException e){
    System.out.println("Exception while processing Resultset: "+e.toString());
}

///尝试通过检查关键条件获取mProduct映射

Map<String, Object> mProductMap     =   new HashMap<String, Object>();
mProductMap     =   lmProducts.stream().filter(m -> m.get("NAME").toString().equalsIgnoreCase(sProductName)).collect(to)

3 个答案:

答案 0 :(得分:2)

您可以collectCollectors.toMap组合的所有条目使用Map

Map<String, Object> mProductMap = lmProducts.stream()
        .flatMap(a -> a.entrySet().stream()) // stream of entries of all maps
        // entries with specific key and value combination
        .filter(m -> m.getKey().equals("NAME") && m.getValue().toString().equalsIgnoreCase(sProductName)) 
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

答案 1 :(得分:1)

您也可以以这种方式进行操作,由于Map具有唯一的键值对,因此检查Map包含该键和值,然后将其收集到Map

Map<String,Object> result = list.stream()
    .filter(m->m.containsKey("NAME") && m.get("NAME").toString().equalsIgnoreCase(sProductName))    // check map contains that key and value
         .collect(Collectors.toMap(key->"NAME",value->value.get("NAME")));  //collect it to Map

注意:如果列表中有两个具有相同键的地图对象,则会抛出异常

java.lang.IllegalStateException: Duplicate key NAME

因此要忽略这种情况,请使用合并功能toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

.collect(Collectors.toMap(key->"NAME",value->value.get("NAME"), (v1,v2)->v1));

答案 2 :(得分:0)

如果我正确获取了您的代码,则说明您正在寻找这样的东西:

Predicate<Map<String, Object>> hasExpectedName = 
    prod -> prod.containsKey("NAME") && prod.get("NAME").toString().equalsIgnoreCase(sProductName);

Map<String, Object> mProductMap = 
    lmProducts.stream()
              .filter(hasExpectedName)
              .findFirst()
              .orElse(null);    // <= return null or a default value
           // .orElseThrow(...) // <= or you can throw an exception if you want

尽管我会采用一些OOP风格:

定义用于保存产品数据的类:

static class Product {
    private String name;
    private String price;
    private String quantity;

    // Constructor & setters & getters
}

然后将数据提取到Product对象中

// ...
System.out.println("PRODUCT\t PRICE\t QUANTITY");
do {
    product = new Product(
        resultSet.getString("NAME"),
        resultSet.getString("PRICE"),
        resultSet.getString("QUANTITY")
    );
    // System.out.println(...);
    products.add(product);
} while (resultSet.next());
// ...

从现在开始,流操作非常简单:

Product product = products.stream()
                          .filter(p -> p.getName().equalsIgnoreCase(sProductName))
                          .findFirst()   // or .findAny()
                          .orElse(null); // or a default value