5

Below is the code for collecting listofmap from resultset and checking the listofmap for a perticular product, if product exists then get that map. Please help me to do it in 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());
}

//Trying to get mProduct map by checking key condition

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

3 Answers 3

2

You can collect all of the entries combined from the map using Collectors.toMap.

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));
Sign up to request clarification or add additional context in comments.

Comments

0

You can do in this way also, Since Map is of unique key value pair check Map contains that key and value, Then collect it to 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

Note Suppose if you have two map object in list with same key then it will throw an exception

java.lang.IllegalStateException: Duplicate key NAME

So to ignore that case use merge function toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

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

Comments

0

If I get your code correctly, you're looking for something like this:

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

Although I would do in a bit more OOP style:

Define a class for holding product data:

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

    // Constructor & setters & getters
}

then fetch the data into Product objects:

// ...
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());
// ...

From now on the stream operations are pretty straightforward:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.