Retrieve array list from Oracle stored procedure - Java - java

I am trying to retrieve a list of objects from a Stored Procedure in Oracle SQL. May you know how can I get an Arraylist from the code below?
ArrayList<String> strings = new ArrayList<>();
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("P_ROUTES");
SqlParameterSource in = new MapSqlParameterSource()
.addValue("V_FIXED_INT", period)
.addValue("V_CARRIER", carrier)
.addValue("V_DATE_RANGE_START", dateRangeStart)
.addValue("V_DATE_RANGE_END", dateRangeEnd);
Map<String, Object> out = jdbcCall.execute(in);
ArrayList obj = (ArrayList) out.get("RET_CURSOR");
Map<String, Object> map = (Map<String, Object>) obj.get(0);
In map object I have the list of key - value pairs.
Check image below:

I am not sure that is the best solution but it works for me. I ll try to find something better. If you have any other suggestion feel free!
Map<String, Object> out = jdbcCall.execute(in);
ArrayList obj = (ArrayList) out.get("RET_CURSOR");
logger.info("Length of retrieved routes from database = " + obj.size());
for (Object o : obj) {
Map<String, Object> map = (Map<String, Object>) o;
for (Map.Entry<String, Object> entry : map.entrySet())
routes.add(entry.getValue().toString());
}

Related

How to iterate List<Map<String, Object>> and add the key and value dynamically in another hash map in java

I'm trying to iterate the List<Map<String, Object>> and want to check if the code is "approved" or not - if code is having value "approved" then I would like to add "id" as Key and "date" as Value in another hashMap.
List<Map<String, Object>> prodIds = ((List<Map<String, Object>>) myIds.get("result"));
This prodIds returns below set of records:
[{id=[14766724], Date=[1999-01-01]}, {id=[49295837], code=[approved], Date=[2003-04-01]}]
[{id=[58761474621], code=[approved], Date=[2017-09-30]}, {id=[3368781], code=[Cancelled], Date=[2014-01-01]}, {id=[48843224], code=[Cancelled], Date=[2009-01-01]}]
I want the output something like this: If code is "approved" - my new hash map should have value like below:
map.put("49295837", "2003-04-01")
map.put("58761474621", "2017-09-30")
Java Code
List<Map<String, Object>> prodIds = ((List<Map<String, Object>>) myIds.get("result"));
System.out.println("prodIds : " +prodIds );
// [{id=[14766724], Date=[1999-01-01]}, {id=[49295837], code=[approved], Date=[2003-04-01]}]
// [{id=[58761474621], code=[approved], Date=[2017-09-30]}, {id=[3368781], code=[Cancelled], Date=[2014-01-01]}, {id=[48843224], code=[Cancelled], Date=[2009-01-01]}]
Map<String, String> newMap = new HashMap<>();
for (Map<String, Object> map : prodIds) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
System.out.println("Key : " +key);
String value = (String) entry.getValue();
System.out.println(" Value : " +value);
}
}
I'm having difficulty how to put the key(id) and value(Date) dynamically if the code value is "approved" into new hash map. It would be really helpful if someone can help me with this.
Appreciated your help in advance!
Thanks
As best as I can determine by your example, this should work. But for each Map<String,Object> I need to know what Object is (e.g. String, List<>, etc).
I am assuming they are lists. If I'm wrong you will get a ClassCastException
public static Map<String, String>
getApproved(List<Map<String, Object>> prodIds) {
Map<String, String> newMap = new HashMap<>();
for (Map<String, Object> map : prodIds) {
if (map.containsKey("code") &&
((List<String>) map.get("code")).get(0)
.equals("approved")) {
newMap.put(((List<String>) map.get("id")).get(0),
(String) ((List<String>) map.get("Date"))
.get(0));
}
}
return newMap;
}
Map<String, String> newMap = getApproved(prodIds);
newMap.entrySet().forEach(System.out::println);
Prints
58761474621=2017-09-30
49295837=2003-04-01
It would help if you could describe all your data structures. Like what is the Object type of map?

Converting HashMap into JSONArray, Values are not coming properly

Am getting response from Elasticsearch with duplicates, to avoid that i used Hashmap implementation and i put all the values into the HashMap object.
After that am iterating over the HashMap object to convert into JSONArray.
Am geting one unique record from distinctObjects (HashMap Object). But after if convert into JSONArray., the length of JSONArray shows 2 it suppose to be 1 and am printing the JSONArray, it shows like below.
JSONArray --->[{"code":"VA1125-GGA-1","id":"code"},{"code":"12816","id":"id"}]
Expected Result should be :
JSONArray --->[{"code":"VA1125-GGA-1","id":"12816"}]
Please find my code below.
JSONObject responseObj;
JSONArray responseArray = new JSONArray();
Map<String, Object> distinctObjects = null;
SearchHit[] searchHits2 = searchResponse2.getHits().getHits();
for (SearchHit hit2 : searchHits2) {
Map<String, Object> sourceAsMap2 = hit2.getSourceAsMap();
distinctObjects = new HashMap<String, Object>();
distinctObjects.put("id", sourceAsMap2.get("id").toString());
distinctObjects.put("code", sourceAsMap2.get("code").toString());
}
Iterator it = distinctObjects.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
responseObj = new JSONObject();
responseObj.put("id", pair.getKey());
responseObj.put("code", pair.getValue());
responseArray.put(responseObj);
it.remove(); // avoids a ConcurrentModificationException
}
System.out.println("Link ID List Size --->"+responseArray.length());
System.out.println("JSONArray --->"+responseArray.toString());
It looks like you're adding both code and id as top level entries to your distinctObjects map which is why you're getting two objects back. Assuming you want to de-dup based on ID your first loop should look something like:
for (SearchHit hit2 : searchHits2) {
Map<String, Object> sourceAsMap2 = hit2.getSourceAsMap();
distinctObjects = new HashMap<String, Object>();
distinctObjects.put(sourceAsMap2.get("id"), sourceAsMap2.get("code").toString());
}
That will give you one entry in distinctObjects for every unique id with a value of the code.
If you wanted you could also add sourceAsMap2 as the value in distinctObjects to maintain the full response if you need more than just the code in downstream processing.

Create a map from an Iterable<Map.Entry> in groovy

I need to fill map with Iterable<Map.Entry>. The following is an original java code:
Iterable<Map.Entry<String, String>> conf;
Iterator<Map.Entry<String, String>> itr = conf.iterator();
Map<String, String> map = new HashMap<String, String>();
while (itr.hasNext()) {
Entry<String, String> kv = itr.next();
map.put(kv.getKey(), kv.getValue());
}
I have to rewrite it in groovy. Is there a concise groovy-way to do it?
I'd use collectEntries for that. It's similar to collect, but it's purpose is to create a Map.
def sourceMap = ["key1": "value1", "key2": "value2"]
Iterable<Map.Entry<String, String>> conf = sourceMap.entrySet()
def map = conf.collectEntries {
[(it.key): it.value]
}
Note the round braces around it.key that allow you to use a variable reference as key of the newly generated Entry.
In Groovy you can use the each closure instead of Iterator as follows
Map<Map.Entry<String, String>> sourceMap = ["key1" : "value1", "key2" : "value2"]
Map<Map.Entry<String, String>> targetMap = [:]
sourceMap.each{ key, value ->
targetMap[key] = value
}
println ​targetMap
Working example here : https://groovyconsole.appspot.com/script/5100319096700928

Error in BulkRequest java API in Elasticsearch : "The number of object passed must be even but was [1]"

I am trying to use map with Bulk Insert Api of ElasticSearch Java Api
public void bulkInsert(List<Map<String,String>> listOfObjects ){
BulkRequestBuilder bulkRequest = client.prepareBulk();
Iterator<Map<String,String>> itr = listOfObjects.iterator();
if (itr.hasNext()){
Map<String,String> document = itr.next();
bulkRequest.add(client.prepareIndex(index, type)
.setSource(document));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
System.out.println(bulkResponse.buildFailureMessage());
}
}
And I am calling this with
Map<String,String> jsonMap = new HashMap<String,String>();
jsonMap.put("name", fullName.toString());
jsonMap.put("file", file);
List<Map<String,String>> listOfObjects = new ArrayList<Map<String,String>>();
listOfObjects.add(jsonMap);
indexService.bulkInsert(listOfObjects);
I am getting following exception
The number of object passed must be even but was [1]
Ok I got the fix :
Use Map<String, Object> instead of Map <String,String>
Map<String,Object> jsonMap = new HashMap<String,Object>();
jsonMap.put("name", fullName.toString());
jsonMap.put("file", file);
List<Map<String,Object>> listOfObjects = new ArrayList<Map<String,Object>>();
listOfObjects.add(jsonMap);
indexService.bulkInsert(listOfObjects);
From ES java api;
Using Map
Map is a key:values pair collection. It represents a JSON structure:
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");

Search a HashMap in an ArrayList of HashMap

I have an ArrayList of HashMap. I want to search a HashMap in it but unable to find a way to achieve this. Please suggest me how it can be done?
Thanks.
Answer to your question the way i understood it!
for (HashMap<String, String> hashMap : yourArrayList)
{
// For each hashmap, iterate over it
for (Map.Entry<String, String> entry : hashMap.entrySet())
{
// Do something with your entrySet, for example get the key.
String sListName = entry.getKey();
}
}
Your Hashmap might use other types, this one uses Strings.
See if this helps:
#Test
public void searchMap() {
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
String keyToSearch = "key2";
for (Map<String, String> map : listOfMaps) {
for (String key : map.keySet()) {
if (keyToSearch.equals(key)) {
System.out.println("Found : " + key + " / value : " + map.get(key));
}
}
}
}
Cheers!
Object myObj;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if( (myObj = curMap.get(myKey)) != null) {
//Stop traversing because we are done
break;
}
}
//Act on the object
if(myObj != null) {
//TODO: Do your logic here
}
If you are looking to get the reference to the Map instead of the object (for whatever reason) same process applies, except you just store the reference to the map:
Map myMap;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if(curMap.get(myKey) != null) {
//Store instance to the map
myMap = curMap;
//Stop traversing because we are done
break;
}
}
//Act on the map
if(myMap != null) {
//TODO: Do your logic here
}
Try below improved code for searching the key in a list of HashMap.
public static boolean searchInMap(String keyToSearch)
{
boolean returnVal = false;
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
for (Map<String, String> map : listOfMaps)
{
if(map.containsKey(keyToSearch))
{
returnVal =true;
break;
}
}
return returnVal;
}
The Efficient way i've used to search a hashmap in an arraylist without using loops. Since loop makes execution time longer
try{
int index = list.indexOf(map); // map is your map to find in ArrayList
if(index>=0){
HashMap<String, String> map = array_list.get(index);
// Here you can get your values
}
}
catch(Exception e){
e.printStackTrace();
Log.i("HashMap","Not Found");
}
if you have an ArrayList like this one: ArrayList<HashMap<String, String>>
and you want to compare one of the values inside the HashMap try this code.
I use it to compare settings of my alarm notifications.
for (HashMap<String, String> map : AlarmList) {
for (String key : map.keySet())
{
if (key.equals("SendungsID"))
{
if(map.get(key).equals(alarmMap.get("AlarmID")))
{
//found this value in ArrayList
}
}
}
}

Categories