How do i convert Array - java

I am trying to serialize Observable Maps with an Serialiazation Proxy.
These two properties need to be saved.
private final MapProperty<Integer, Cargo> allCargoStoredMap;
private final MapProperty<Cargo, CargoLogisticData> cargoLogisticDataMap;
I thought i can save the values in an array like this:
this.cargoLogisticDataAsArray = warehouseManagement.getCargoCargoLogisticDataMap().values().toArray(new CargoLogisticData[0]);
this.cargoAsArray = warehouseManagement.getAllCargoStoredMapProperty().values().toArray(new Cargo[0]);
Then i want to pass i to an Constructor, and rebuild the properties.
public Constructor (List<Cargor> cargos, List<CargoLogisticData>) {
ObservableMap<Integer, Cargo> cargos = FXCollections.observableHashMap();
//How do i add my cargos to a map?
this.allCargoStoredMap = new SimpleMapProperty<>(cargos);
}
Any Idea how i can add the the List Entrys to my map?
I thought i maybe have to save 4 Arrays. Two with key, two with values. And then add those again.
Any Ideas ?

This can be a simple solution if I don't get it wrong
allCargoStoredMap.values().stream().forEach(cargo -> {
CargoLogisticData logisticsData=cargoLogisticDataMap.get(cargo);
/*
You have cargo and related logistics data here.
You can create which data model you want to store and use it
*/
})

Related

How to change a set to list of different types in java?

Now how to store that values of set in a list. Here the set and list is of different type(ProductAttribute and PersistableProductAttribute).
for(ProductRelationship productrelationship:productRelationshipList)
{
Product product=productrelationship.getRelatedProduct();
PersistableProduct ppTem=new PersistableProduct();
Set<ProductAttribute> aSet = product.getAttributes();
List<PersistableProductAttribute> aList = new ArrayList<PersistableProductAttribute>();
// I need to store here in a list.
}
Its just a simple one I have got it after trying several times by myself.First I need to create a set for PersistableProductAttribute and I have to get the attributes of it using loop and I need to copy that set to list. Now it works fine because the set and list are same type. So we can copy a set to list using add() method in java.
Set<PersistableProductAttribute> ppaSet = new
PersistableProductAttribute<>();
for(ProductAttribute x:aSet)
{
// Get all the attributes here using get()
//and set() methods
// Copy the set to list as follows,
aList.add(ppaSet);
}

Update existing entry within a map attribute using DynamoDBMapper

I'm using DynamoDBMapper from the AWS Java SDK and working with a fairly simple item: it has a string attribute (used as the hash key) and a map attribute.
#DynamoDBTable(tableName = "MyTable")
public class MyItem {
private String myStringAttr;
private Map<String, String> myMapAttr;
#DynamoDBHashKey(attributeName = "MyStringAttribute")
public String getMyKeyAttr() { return myKeyAttr; }
public void setMyKeyAttr(String myKeyAttr) { this.myKeyAttr = myKeyAttr; }
#DynamoDBAttribute(attributeName = "MyMapAttribute")
public Map<String, String> getMyMapAttr() { return myMapAttr; }
public void setMyMapAttr(Map<string, string> myMapAttr) { this.myMapAttr = myMapAttr; }
}
I can read and write my object using the load() and save() methods just fine. The issue I'm running into is when I need to update or add a single entry in the map for an existing item in the table. Without knowing the existing entries of the map for said item (and I don't want to perform a load() each time before I attempt to update or add), the best I seem to be able to do is wipe out the entire map and replace it with the single entry I'm trying to update or add. Is it possible to add/update a single entry to an existing item's map attribute using the DynamoDBMapper?
I've looked at the various options provided by DynamoDBSaveExpression and DynamoDBMapperConfig. The closest option I can find is DynamoDBMapperConfig.SaveBehavior.APPEND_SET, but this is for set type attributes rather than the map type I'm using.
I'm able to achieve this exact use case using the Document API's updateItem() method along with an UpdateItemSpec containing an UpdateExpression as shown below. This will add a new entry to the map if the given key doesn't yet exist, or update the value to the one specific if an existing entry does exist, all without touching the other entries in the map. However, I have found the Document API rather cumbersome to work with and would prefer to stick with the DynamoDBMapper if at all possible.
Table table = dynamoDB.getTable("MyTable");
UpdateItemSpec updateItemSpec = new UpdateItemSpec()
.withPrimaryKey("MyStringAttribute", 1)
.withUpdateExpression("set #mma.#mek = :mev")
.withNameMap(new NameMap()
.with("#mma", "MyMapAttribute")
.with("#mek", "SomeMapEntryKey")
.withValueMap(new ValueMap()
.withString(":mev", "Some map entry value"));
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
One possible solution would be:-
1) Get the data from the table "MyTable" using DynamoDBMapper load
2) Add new entries to the map in the object retrieved in step 1 and save that object using DynamoDBMapper with config as mentioned below
DynamoDBMapperConfig dynamoDBMapperConfig = new DynamoDBMapperConfig(SaveBehavior.UPDATE);
I know that this is a two step process. However, when I was in the same situation, I have tried a lot and couldn't find any solution with single direct update for "Map" data type using DynamoDBMapper.
Hope this helps!

Best way to save some data and then retrieve it

I have a project where I save some data coming from different channels of a Soap Service, for example:
String_Value Long_timestamp Double_value String_value String_value Int_value
I can have many lines (i.e. 200), with different values, like the one above.
I thought that I could use an ArrayList, however data can have a different structure than the one above, so an ArrayList maybe isn't a good solution in order to retrieve data from it.
For example above I have, after the first two values that are always fixed, 4 values, but in another channel I may have 3, or 5, values. What I want retrieve data, I must know how many values have a particular line, and I think that Arraylist doesn't help me.
What solution could I use?
When you have a need to uniquely identify varying length input, a HashMap usually works quite well. For example, you can have a class:
public class Record
{
private HashMap<String, String> values;
public Record()
{
// create your hashmap.
values = new HashMap<String, String>();
}
public String getData(String key)
{
return values.get(key);
}
public void addData(String key, String value)
{
values.put(key, value);
}
}
With this type of structure, you can save as many different values as you want. What I would do is loop through each value passed from Soap and simply add to the Record, then keep a list of Record objects.
Record rec = new Record();
rec.addData("timestamp", timestamp);
rec.addData("Value", value);
rec.addData("Plans for world domination", dominationPlans);
You could build your classes representing the entities and then build a parser ... If it isn't in a standard format (eg JSON, YAML, ecc...) you have no choice to develop your own parser .
Create a class with fields.
class ClassName{
int numberOfValues;
String dataString;
...
}
Now create an ArrayList of that class like ArrayList<ClassName> and for each record fill that class object with numberOfValues and dataString and add in Arraylist.

Using one variable as an another variable of different data type but the same name

I am using a class where I am taking input as the file name and the file location. I have a pre defined file names, so I will match the predefined file names with the file name that I received and then store the values accordingly. Please look at the code below
//Set of storage maps and tables
public class storage
{
//Storage set
public static Set<Integer> tiger = new HashSet<Integer>();
//Storage set
public static Set<Integer> lion = new HashSet<Integer>();
//This is the table used for storing the browser customer count
public static Table<String,String,Integer> elephant = HashBasedTable.create();
//Storage map
public static Map<String, String> monkey = new HashMap<String, String>();
public static void storeDataDirector(String fileLocation,String fileName) throws Exception
{
if (fileName = monkey)
**update the "monkey map"**
}
This is my problem, also I have lot of maps and tables to be used so I wouldn't be able to use multiple if conditions and then check and update the same.
What I would like to know is the below
As I have said earlier, The file name that I am sending to the program which is "String filename" has the same name of the "Map monkey" but the former is a String and the latter is the map. I would like to know if I will be able to use the string variable as a reference to the map instance as both of them have the same name . This will highly avoid the if conditions that I am using in the program and thus I would like to possible solution for this ... Anything related to type caseting ort
You need to have another Map - whose key is a String and value is a Map. Something like Map<String,Map> allMaps = new HashMap<String,Map>()
Once you have this map , populate it with all your filenames and the corresponding maps monkey.
allMaps .put("monkey", monkey)
If a string filename corresponds to not a map but to a set , then you need to declare something more general Map<String,Object> allMaps = new HashMap<String,Object>(). Ofcourse this means you need to cast the value to its particular type before you can do any meaningful thing with it.
Then , to use this map , use your filename argument
Map monkeyAgain = allMaps.get(filename)
You can use reflection:
Storage.class.getField(fileName).get(null)
You will still have to cast the returned object. I do not think this the right approach.
The idea is to relate them in a Map, and use the file name as a key for example
Map<String, Map<String, String>>
// file store structure
If you need a generic solution, you could solve this by implementing an abstraction of your store structure, by implementing an interface similar to this one:
// T is the store type and U is the original type (String from file for instance...)
public interface StoreUnit<T, U> {
void update(U record);
List<T> list();
}
so you will have an implementation for each case (Set, Map, Table ...) and will relate it in a map using the file name as key.
monkeyFileName => MapStoreUnit<Entry<String,String>,String>
tigerFileName => SetStoreUnit<Integer, String>
elephantFileName => TableStoreUnit<Entry<Entry<String,String>,String>,String> // not sure if for Table there is something better than Entry ;)
When you wanna update some store you perform a get over the map using the file name as key, and invoking update method implemented with the record (that could be an String, complex Object) and so on. When you need to read something from there you could use the list method.

adding a key to HashMap without the value?

Is there a way to add a key to a HashMap without also adding a value? I know it seems strange, but I have a HashMap<String, ArrayList<Object>> amd I want to first be able to create keys as needed and then check if a certain key exists and, if so, put the appropriate value, namely the ArrayList<Object>
Was that confusing enough?
Since you're using a Map<String, List<Object>>, you're really looking for a multimap. I highly recommend using a third-party library such as Google Guava for this - see Guava's Multimaps.
Multimap<String, Object> myMultimap = ArrayListMultimap.create();
// fill it
myMultimap.put("hello", "hola");
myMultimap.put("hello", "buongiorno");
myMultimap.put("hello", "สวัสดี");
// retrieve
List<String> greetings = myMultimap.get("hello");
// ["hola", "buongiorno", "สวัสดี"]
Java 8 update: I'm no longer convinced that every Map<K, SomeCollection<V>> should be rewritten as a multimap. These days it's quite easy to get what you need without Guava, thanks to Map#computeIfAbsent().
Map<String, List<Object>> myMap = new HashMap<>();
// fill it
myMap.computeIfAbsent("hello", ignored -> new ArrayList<>())
.addAll(Arrays.asList("hola", "buongiorno", "สวัสดี");
// retrieve
List<String> greetings = myMap.get("hello");
// ["hola", "buongiorno", "สวัสดี"]
I'm not sure you want to do this. You can store null as a value for a key, but if you do how will be able to tell, when you do a .get("key") whether the key exists or if it does exist but with a null value? Anyway, see the docs.
You can put null values. It is allowed by HashMap
You can also use a Set initially, and check it for the key, and then fill the map.
Yes, it was confusing enough ;) I don't get why you want to store keys without values instead just putting empty arraylists instead of null.
Adding null may be a problem, because if you call
map.get("somekey");
and receive a null, then you do not know, if the key is not found or if it is present but maps to null...
//This program should answer your questions
import java.util.*;
public class attemptAddingtoHashMap { //Start of program
//MAIN METHOD #################################################
public static void main(String args[]) { //main begins
Map<String, ArrayList<Object>> hmTrial = new HashMap<String, ArrayList<Object>>();
ArrayList alTrial = new ArrayList();//No values now
if (hmTrial.containsKey("first")) {
hmTrial.put("first", alTrial); }
else {hmTrial.put("first",alTrial);}
//in either case, alTrial, an ArrayList was mapped to the string "first"
//if you choose to, you can also add objects to alTrial later
System.out.println("hmTrial is " + hmTrial); //empty now
alTrial.add("h");
alTrial.add("e");
alTrial.add("l");
alTrial.add("l");
alTrial.add("o");
System.out.println("hmTrial is " + hmTrial);//populated now
} //end of main
//#############################################################################################################
} //end of class
//Note - removing objects from alTrial will remove the from the hashmap
//You can copy, paste and run this code on https://ide.geeksforgeeks.org/

Categories