I've a row in db returned by query below. Columns to select include rec, head, amount. I want to sort the rows by head column. I tried Map where string for head and list for other two columns.
I've hit the wall with my non-working code posted below. How would I append another list to list of repeated key. Documentation says it replaces the value for same key whereas I need it appended to the list value. I would be really greatful for any help.
Query q= session.createQuery("select tally_receipt_prefix, tally_receipt_no, tally_head, tally_amount from Tally_table where tally_system_date='"+fmtd_date+"' and tally_dbcr_indicator='DB' and tally_mode='Ca' order by tally_head,tally_receipt_prefix,tally_receipt_no"); System.out.println("query "+q);
List heads=new ArrayList();
for(Iterator it=q.iterate(); it.hasNext(); )
{
Object[] row= (Object[]) it.next();
payincash1=new LinkedHashMap<String, List>();
heads.add((String)row[2]);
List tails = null;
tails=new ArrayList();
tails.add((String)row[0]);
tails.add((String)row[1]);
tails.add((String)row[3]);
System.out.println("heads in dao from iter 1: "+heads);
System.out.println("tails in dao from iter1 on: "+tails);
if(heads.contains((String)row[2])) // for head in temp list
{
System.out.println("in first if");
if(payincash1.containsKey((String)row[2]))
{
System.out.println("map if repeat: "+payincash1);
payincash1.put((String)row[2],tails);
}
}
else
{
System.out.println("map if not repeat: "+payincash1);
payincash1.put((String)row[2], tails);
}
}
Sounds more like you want a list of lists
Something like Map<String, List<List>>
Then you'd end up with something like...
Map<String, List<List>> payincash1 = new LinkedHashMap<String, List<List>>();
heads.add((String) row[2]);
List tails = null;
tails = new ArrayList();
tails.add((String) row[0]);
tails.add((String) row[1]);
tails.add((String) row[3]);
System.out.println("heads in dao from iter 1: " + heads);
System.out.println("tails in dao from iter1 on: " + tails);
List master = payincash1.get((String)row[2]);
if (master == null) {
master = new List();
payincash1.put((String)row[2], master);
}
master.add(tails);
Now, personally, I'd be creating a "data" object that would contain all this information.
public class MyData {
private String rec, head, amount, ??; // Apparently you have another variable I don't know about
public MyData(String rec, String head, String amount, String ??) {
// Initalise...
}
// Setters and getters not inclueded
}
Then you could do something like this...
Map<String, List<MyData>> payincash1 = new LinkedHashMap<String, List<MyData>>();
MyData data = new MyData(row[0], row[1], row[2], row[3]);
List master = payincash1.get((String)row[2]);
if (master == null) {
master = new List<MyData>();
payincash1.put((String)row[2], master);
}
master.add(data);
Which is a little cleaner (IMHO)
From what I understand you need Multimap of guava library.
Related
Im trying to delete all items in my table in dynamodb but it does not work.
try {
ScanRequest scanRequest = new ScanRequest().withTableName(table);
ScanResult scanResult = null;
do {
if (Check.nonNull(scanResult)) {
scanRequest.setExclusiveStartKey(scanResult.getLastEvaluatedKey());
}
scanResult = client.scan(scanRequest);
scanResult.getItems().forEach((Item) -> {
String n1 = Item.get("n1").toString();
String n2 = tem.get("n2").toString();
DeleteItemSpec spec = new DeleteItemSpec().withPrimaryKey("n1", n1, "n2", n2);
dynamodb.getTable(table).deleteItem(spec);
});
} while (Check.nonNull(scanResult.getLastEvaluatedKey()));
} catch (Exception e) {
throw new BadRequestException(e);
}
n1 is my Primary partition key
n2 is my Primary sort key
The best approach to delete all the items from DynamoDB is to drop the table and recreate it.
Otherwise, there are lot of read capacity and write capacity units being used which will cost you.
Dropping and recreating the table is the best approach.
PREAMBLE: While a scan operation is expensive, I was needing this answer for initialising a table for a test scenario (low volume). The table was being created by another process and I needed the test scenario on that table, I could therefore not delete and recreate the table.
ANSWER:
given:
DynamoDbClient db
static String TABLE_NAME
static String HASH_KEY
static String SORT_KEY
ScanIterable scanIterable = db.scanPaginator(ScanRequest.builder()
.tableName(TABLE_NAME)
.build());
for(ScanResponse scanResponse:scanIterable){
for( Map<String, AttributeValue> item: scanResponse.items()){
Map<String,AttributeValue> deleteKey = new HashMap<>();
deleteKey.put(HASH_KEY,item.get(HASH_KEY));
deleteKey.put(SORT_KEY,item.get(SORT_KEY));
db.deleteItem(DeleteItemRequest.builder()
.tableName(TRANSACTION_TABLE_NAME)
.key(deleteKey).build());
}
}
To delete all the items from the table first you need to perform scan operation over the table which will results you an scanoutcome. Using the iterator loop over the sacnoutcome with the primary key and it's primary key value.This will be one of the approach to delete all the items from the table. Hope that this code will work you. Thanks
Table table = dynamoDB.getTable(your_table);
ItemCollection<ScanOutcome> deleteoutcome = table.scan();
Iterator<Item> iterator = deleteoutcome.iterator();
while (iterator.hasNext()) {
your_table.deleteItem("PrimaryKey", iterator.next().get("primary key value"));
}
//May be we can make it look generic by reading key schema first as below
String strPartitionKey = null;
String strSortKey = null;
TableDescription description = table.describe();
List<KeySchemaElement> schema = description.getKeySchema();
for (KeySchemaElement element : schema) {
if (element.getKeyType().equalsIgnoreCase("HASH"))
strPartitionKey = element.getAttributeName();
if (element.getKeyType().equalsIgnoreCase("RANGE"))
strSortKey = element.getAttributeName();
}
ItemCollection<ScanOutcome> deleteoutcome = table.scan();
Iterator<Item> iterator = deleteoutcome.iterator();
while (iterator.hasNext()) {
Item next = iterator.next();
if (strSortKey == null && strPartitionKey != null)
table.deleteItem(strPartitionKey, next.get(strPartitionKey));
else if (strPartitionKey != null && strSortKey != null)
table.deleteItem(strPartitionKey, next.get(strPartitionKey), strSortKey, next.get(strSortKey));
}
I'm using Java and Infusionsofts API to get a list of contacts based on the customer id. I can't figure out a way to do this. I'm using Googles Guava to use multimap but it's producing an error:
org.apache.xmlrpc.common.XmlRpcExtensionException: Serializable objects aren't supported, if isEnabledForExtensions() == false
So now i'm trying hashmap and i'm inserting "Id" as the key and the customer id as the value but there's always one entry in the hashmap.
How can I add to the parameters variable a map that contains:
["Id",11111]
["Id",22322]
["Id",44444]
List parameters = new ArrayList();
parameters.add(APP_ID);
parameters.add(TABLE_NAME);
parameters.add(LIMIT);
parameters.add(pageNumber);
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(int customerId : customerIds){
map.put("Id", customerId);
}
//PROBLEM IS HERE
parameters.add(map);
//THIS IS THE PROBLEM, I NEED TO ADD ["Id", customerId] multiple
//times with the customerId being different but since there's a hashmap
//There's always 1 entry in the map
String[] fields = {"Email","FirstName"};
parameters.add(fields);
Object[] contacts = null;
try{
contacts = ( Object [] ) client.execute("DataService.query",parameters);
}catch(XmlRpcException e){
e.printStackTrace();
}
for (int i = 0; i < contacts.length; i++) {
Map contact = (Map) contacts[i];
System.out.println(contact+"\n\n");
}
I use following complex data structure.
departures = new TreeMap<String, Map<String, Set<MyObject>>>();
arrivals=new HashMap<String, Set<MyObject>>();
flights=new HashSet<MyObject>();
Then I use loops (I also tried other loops).
for(String dep: nizDep){
for(String arr: nizArr){
for(MyObject flight: _flights){
if(flight.getFrom().equalsIgnoreCase(dep)&&flight.getTo().equalsIgnoreCase(arr)){
flights.add(flight);
}
}
if(!flights.isEmpty()){
arrivals.put(arr, flights);
flights.clear();
}
}
if(!arrivals.isEmpty()){
departures.put(dep, arrivals);
arrivals.clear();
}
}
System.out.println(departures.size()); //result 14
System.out.println(departures.containsKey("Madrid")); //result true
arrivals=departures.get("Madrid");
System.out.println(arrivals.size()); //result 0, arrivals is empty. WHY?
My question is how to use this complex data structure and how to retrieve arrivals from departures?
System.out.println(arrivals.size()); //result 0, arrivals is empty. WHY?
BECAUSE When you call flights.clear(); after arrivals.put(arr, flights); or arrivals.clear(); after departures.put(dep, arrivals);, this clears your original objects(flights and arrivals). Please bring your initialization statements i.e.
Map<String, Set<MyObject>> arrivals=new HashMap<String, Set<MyObject>>();
Set<MyObject>(); flights=new HashSet<MyObject>();
within the for loops or replace that statement as below:
if(!flights.isEmpty()){
Set<MyObject> newflights=new HashSet<MyObject>();
newflights.addAll(flights); //copy elements to new set
arrivals.put(arr, newflights);
flights.clear();
}
Same you may do with departures.
Now for retrievals:
Set<String> arrivalKeys = departures.keySet();
Interator<String> arrIter = arrivalKeys.iterator();
while(arrIter.hasNext()){
String arrKey = arrIter.next();
Map<String, Set<MyObject>> arrivals = departures.get(arrKey );
//use your arrivals map object
}
Same you can do to retrieve flights from arrivals e.g.
for each arrivals retrieved as above:
Set<String> flightKeys = arrivals.keySet();
Interator<String> flIter = flightKeys.iterator();
while(flIter.hasNext()){
String flKey = flIter.next();
Set<MyObject> flights = arrivals.get(flKey );
//use your flights set object
}
arrivals=new HashMap<String, Set<MyObject>>();
departures = new TreeMap<String, Map<String, Set<MyObject>>>();
for(String dep: nizDep){
for(String arr: nizArr){
for(MyObject flight: _flights){
if(flight.getFrom().equalsIgnoreCase(dep)&&flight.getTo().equalsIgnoreCase(arr)){
flights=new HashSet<MyObject>();
flights.add(flight);
arrivals.put(arr, flights);
departures.put(dep, arrivals);
}
}
}
}
System.out.println(departures.size()); //result 14
if(departures.containsKey("Madrid")) {
arrivals=departures.get("Madrid");
System.out.println(arrivals.size());
}
In case you want to keep a one-to-one mapping between arrivals and flights, then this code works. In case you want to keep a global structure of maintaining the set of flights then you'll have to create another global gflights object and put every flights object into it.
I want to get all the objects from the list and put them into a Map grouped by creation date, which means the map is like this: Map<String, List<MyObject>>. The MyObject object has a field that stores its creation date.
I've thought of doing a nested while loop that looks like this:
public Map<String, List<Expense>> getExpensesSorted(SortType type){
Map<String, List<Expense>> map = new HashMap<String, List<Expense>>();
List<Expense> expenses = getAllExpenses(budgetId).getExpenses()
.getList();
if (type.equals(SortType.DAY)) {
Iterator<Expense> expIter = expenses.iterator();
while (expIter.hasNext()) {
List<Expense> list = new ArrayList<Expense>();
Expense exp = (Expense) expIter.next();
list.add(exp);
String day = exp.getDate().format("YYYY-MM-DD");
expIter.remove();
while (expIter.hasNext()) {
Expense exp2 = (Expense) expIter.next();
if (exp2.getDate().format("YYYY-MM-DD").equals(day)) {
list.add(exp2);
expIter.remove();
}
}
map.put(day, expenses);
}
} else if (type.equals(SortType.WEEK)) {
...
} else if (type.equals(SortType.TYPE)) {
...
} else if (type.equals(SortType.CATEGORY)) {
...
}
return map;
}
But this is wrong, it only gets all the ones that have the same day as the first element, so my map ends up having only one element.
I seriously don't know how to solve this...
Thanks in advance for any help.
Map<Data, List<MyObject>> result = new HashMap<Data, List<MyObject>>;
for (List<MyObject> list : myMap.values()) {
for (MyObject myObject : list) {
Date date = myObject.getDate();
List<MyObject> newList = result.get(date);
if (newList == null) {
newList = new Arraylist<MyObject>;
result.put(date. newList);
}
newList.add(myObject);
}
}
Something like this should do the job. I didn't compile it though.
while (iter.hasNext()) {
MyObject obj = (MyObject) iter.next();
String day = obj.getDate().format("YYYY-MM-DD");
if(!map.containsKey(day)) {
map.put(day, new ArrayList<MyObject>());
}
List<MyObject> list = map.get(day);
list.add(obj);
map.put(day, list);
}
I am new in Android development, and I am trying to receive a HashMap in RESULT by using XMLRPC but every time it's crash the application, this is my code please advice me :
Object RESULT = XMLRPCClient.callEx(methodname,new Object[] {params});
Map FRESULT= (Map) RESULT;
I have been dealing with this also and managed to get the values this way:
try {
Object[] answer = (Object[]) client.call("call", sessionId, method, params);
HashMap map = (HashMap) answer[0]; // get first item of the response because in my case the response was an array of Objects with one item in it holding the HashMap
Object[] records = (Object[]) map.get("records"); // I only needed values from "records" key
for (int i = 0; i < records.length; i++) {
HashMap record = (HashMap) records[i]; // create another map from the records values, in my case uid's of categories
Category cat = new Category(); // creating new instance of my Category class
cat.setCatUid((String) record.get("uid")); // calling a method of the Category class to set Uid to the value from record HashMap
m_categories.add(cat); // this adds it to my ArrayList<Category>
}
} catch (XMLRPCException e) {
Log.e(method, "Exception", e);
}
I'm sure it's a mess, I'm noob in Java myself, but it worked for me. Hope it helps :)
Now the Application pass this peacefully after implementing :
Object RESULT = XmlRpcConnect.ServerCall_a(method,new Object[] {params});
Map<String, Object> FRESULT= (HashMap<String, Object>) RESULT;
with some changes in my XmlRpcConnect Class:
#SuppressWarnings("unchecked");
public static Object ServerCall_a(String method, Object[] params){
XMLRPCClient client = new XMLRPCClient(server);
HashMap<String, Object> result=null;
try{
result = (HashMap<String, Object>) client.callEx(method, params);
}
catch(XMLRPCFault f){
// result = ("Fault message: " + f.getMessage());
}
catch(XMLRPCException e){
// result = ("Exception message: " + e.getMessage());
}
return result;
}
but when trying to extract the values it's crash again , any advice :
if (FRESULT.get("status") == null) {
result = (String) FRESULT.get("status");
toastDialog(result);
}