I have stored a key-value pair in the hash map where key is a string ID and value is List of tuple .I need to fetch the data present in the list and insert into Database. What is the code logic to iterate over the List of tuple inside a map and get the data from the list?
One of the ways is using Java 8 streams
map.values() // get all the list of tuples i.e. values
.stream() // java 8 stream api
.flatMap(listOfTuple -> listOfTuple.stream()) // flattening the list
.forEach(tuple -> doWhatEverWithTuple(tuple)); // use individual tuple
You can get the values from map using map.values method or you can use Entry if you need to add some conditions based on keys.
Map<String, List<Tuple>> data = somemethod();
for(List<Tuple> tuples : data.values()) {
//... some code
}
or
for(Map.Entry<String, List<Tuple>> entry : data.entrySet()) {
String key = entry.getKey();
List<Tuple> tuples = entry.getValue();
// ... Some code
}
Related
I am using a multimap like this
Multimap<String, MyObject> tasksMap = ArrayListMultimap.create();
Where there can be multiple items for the same key, get the List value for every key in the map?
.asMap() lets you get a map and you can then iterate over its .entrySet().
Something like
for (Entry<String, Collection<MyObject>> e : tasksMap.asMap().entrySet()) {
String key = e.getKey();
Collection<MyObject> values = e.getValue();
...
}
Just use get method to get all values for a key
List<MyObject> values = tasksMap.get(key);
or use values to get all values for every key in map
Collection<List<MyObject>> values = tasksMap.values();
or entries to get all entries
Collection<Map.Entry<String, List<MyObject>>> entries = tasksMap.entries()
I am trying to figure out how to retrieve a value that is stored in an ArrayList, stored in a Hashmap.
Here's what I have:
HashMap<String, ArrayList<Record>> records = new HashMap<>();
The key in this hashmap is not what I am looking for. There is a method inside of the Record object called getRecordId() and I want to be able to evaluate whether or not this recordId, through an if statement, exists in the ArrayList.
Example:
if(records.values.exists(recordId)){ ...do something ...}
Essentially, I want to loop through all the values in the ArrayList to see if that record ID exists, and if it does, I will store the key and compute some things. How to I do this?
Edit: right after posting this question, I think I am on to something. How about this:
Set<Map.Entry<String, ArrayList<Record>>> entrySet = records.entrySet();
for(Map.Entry<String, ArrayList<Record>> data : entrySet)
{
for(Record entry : data.getValue())
{
if(recordId.equals(entry.getRecordId()))
{
// Do something here
return "";
}
}
}
I need to leave the loops if the record ID has been found, because record IDs are unique.
You can use here Hashmap.entrySet() to get the list of all the keys, and iterate through that key set, and check if recordId exists in the ArrayList for that particular iteration, then store the key and do your computations.
If you are not sure about the syntax and usage of entrySet then you can look into it here - https://www.geeksforgeeks.org/iterate-map-java/
for (Map.Entry<String, ArrayList> data : records) {
ArrayList list = (ArrayList) data.getValue();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(recordId)) {
// do something
}
}
}
If you are using Java 8 you can use stream:
//List of keys which contains your desired Record at it's value(ArrayList)
List<String> requiredListOfKeys = records.keySet().stream()
.filter(x -> records.get(x)
.contains(record))
.collect(Collectors.toList());
One way to go would be to stream the map values, and for each value (which is a list), stream it and find the first Record instance that matches your search criteria. Then, if such record was found, do whatever you want to do with it:
boolean found = records.values().stream()
.flatMap(List::stream) // or .flatMap(list -> list.stream())
.filter(entry -> recordId.equals(entry.getRecordId()))
.findFirst()
.ifPresent(entry -> {
// do something with the found record
});
You can use the following syntax :
records.forEach((k, v) -> {
if (v.contains(recordId)) {
// do something with 'k'
}
});
Here we are iterating over the map using forEach. The k stands for the key and the v stands for the value. You can also achieve the same using the entrySet
records.entrySet().forEach(e -> {
if (e.getValue().contains(recordId)) {
// do something with 'e.getKey()'
}
});
In below code am getting map of documents i want to add new key & value to documents object.
public List<Map<String, Object>> getDocuments() {
String sql = "Select * from docs";
List<Map<String, Object>> Documents = jdbcTemplateObject.queryForList(sql);
return Documents;
}
Output:
[{Id=DOC10,Name=Test Document,Date=10-12-17}],
[{Id=DOC11,Name=Sample Document,Date=15-12-17}]
How can I add a new k,v to this List<Map> object so that output looks like this?
[{Id=DOC10,Name=Test Document,Date=10-12-17,Access=true}],
[{Id=DOC11,Name=Sample Document,Date=15-12-17,Access=true}]
You can just iterate through the list and add a new key value pair to each map:
for(Map<String, Object> map : Documents){
map.put("Access", true);
}
Another solution, depending on what jdbcTemplateObject.queryForList(sql); do is to add the value in your query.
select *, 1 as Access from docs
this seems to iterate on each column to insert it in the Map.
NOTE: the query is not necessarily DBMS independent ! Boolean is not really a SQL type
Iterate over the List> Documents & get Map Object and put key value pair in that Map object
e,g
List<Map<String, Object>> Documents = jdbcTemplateObject.queryForList(sql);
for (Map<String, Object> map : Documents) {
map.put(key, value);
}
I have a Singleton class that inside has a HashMap. The HashMap is made of String and Set<String>:
private Map<String, Set<String>> mMap = new HashMap<>();
What I want to achieve?
Remove a given item from all the Set values inside the Map. For example:
mMap.put(keyName, new HashSet<String>())
....
mViewsSwipeStates.get(keyName).add("1");
mViewsSwipeStates.get(keyName).add("2");
mViewsSwipeStates.get(keyName).add("3");
....
//Remove an item from the set
mMap.values().remove("3"); //Does not work
What is the correct way to remove an item from inside the Set?
I'm assuming you want to remove productCode from all the values of the Map (and not just from the value of a specific key).
You have to iterate over all the values of the Map, and remove from each of them the required element :
mMap.values().forEach(v->v.remove(productCode));
This code assumes there are no null values in the Map.
EDIT :
In Java 7 you can write:
for (Set<String> value : mMap.values()) {
value.remove(productCode);
}
Iterate over all map entries, mutating the value for each:
map.forEach((k, v) -> v.remove(productCode)};
using java 8 and lambda expressions
map.forEach((key, value) -> value.remove(productCode));
I am trying to add map values to list for my scenario as below.
I have select statement which returns n-no of columns and row, I am storing them into List of Hash Map of type String and pass it to some other method to produce an EXCEL file out of the result.
i am unable to see any data in the list
Please advice where i am going wrong.
while (result.next()) {
resultValues.put("PARTC_ID",result.getString("PARTC_ID"));
resultValues.put("FILE_NME",result.getString("FILE_NME"));
resultValues.put("LOC_ID",result.getString("LOC_ID"));
resultValues.put("CRTE_DTE",result.getString("CRTE_DTE"));
resultValues.put("CRTE_BY",result.getString("CRTE_BY"));
value.add(resultValues); resultValues.clear(); System.out.println(value);
}
You're clearing your Map after adding it to the List. The Map references are all thus the same (and empty)... I think you want to make this change -
// resultValues.clear(); // No, if you need another Map... do this
resultValues = new HashMap<String, String>();
Then to iterate your value List try
for (HashMap<String, String> map : value) {
for (String key : map.keySet()) {
System.out.printf("key[%s] = %s\n", key, map.get(key));
}
}