Chammu
Chammu

Reputation: 113

Is there any way to replace a Map value inside a List using java 8?

I have the below piece of code. I need to replace the Map's value based on the key,value that i have already.

Definition class has the below variables:

private Map<String, String> rows;
private String tableName;

I have tried with the below code. Can this be achieved in any other simpler way?

/*Definitions*/
Definition definitionObj = new Definition();
definitionObj.setTableName("TABLE1");
Map map = new HashMap<String,String>();
map.put("1","one");
map.put("2","two");
map.put("3","threee");
definitionObj.setRows(map);

Definition definitionObj1 = new Definition();
definitionObj1.setTableName("TABLE2");
Map map1 = new HashMap<String,String>();
map1.put("4","one");
map1.put("5","two");
map1.put("6","threee");
definitionObj1.setRows(map1);

String key1 = "2";
String value1 = "modifiedvalue"; /*the value that i need to set*/

List<Definition> myList = Arrays.asList(definitionObj,definitionObj1);

Definition result1 = myList.stream()                       
        .filter(x -> "TABLE1".equals(x.getTableName()))        
        .findAny()                                     
        .orElse(null);
result1.getRows().replace(key1,value1);
System.out.println(result1);

Upvotes: 2

Views: 2881

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

The findAny method returns an optional which you can map to a dictionary and then use ifPresent to update the dictionary value for a given key. Here's how it looks.

myList.stream().filter(x -> "TABLE1".equals(x.getTableName()))
    .findAny().map(Definition::getRows)
    .ifPresent(m -> m.put(key1, value1));

Apart from that, your Map declaration should be changed to use parameterized types instead of raw types. Change it like so,

Map<String, String> map = new HashMap<>();

However, a much better approach would be to declare a new API method in your Definition class to update the internal state given the required parameters and then use it in your client code. Here's how it looks.

public void updateRows(String key, String value) {
    if (rows.containsKey(key))
        rows.put(key, value);
}

myList.stream().filter(x -> "TABLE1".equals(x.getTableName())).findAny()
                .ifPresent(d -> d.updateRows(key1, value1));

While the former violates encapsulation, the latter doesn't.

Upvotes: 4

Related Questions