How to convert SET to array in APEX? - salesforce

I have map with key and value and my goal is to get list of 'key'.
I am thinking to get it to the array or List.
Got to the point where I have key values in the SET but haven't figure out
how to convert to the array.
below is my code:
Map<String, String> mmm = new Map<String, String>();
mmm.put('one', 'oneee');
mmm.put('two', 'twooo');
mmm.put('three', 'threeee');
mmm.put('four', 'fourff');
//outputs values in the map
system.debug('=======values()==========>' + mmm.values());
//outputs key in the map
system.debug('=======keyset()===========>' + mmm.keyset());
//get keys in the type SET
SET<string> s = mmm.keyset();
//returns 4
system.debug('------------------------------------' + s.size());
s.arrayTo() //this method does not exist :(

Use List.addAll method?
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_methods_system_list.htm?SearchType=Stem
If not - you could always manually loop through the set...

Could you use:
Set keys = mmm.keySet();
List keyList = new List(keys);

You should always used generics for type safety.
Map<String, String> mmm = new Map<String, String>();
mmm.put('one', 'oneee');
mmm.put('two', 'twooo');
mmm.put('three', 'threeee');
mmm.put('four', 'fourff');
List<String> lstKeys = new List<String>(mmm.keyset());
System.debug('Output : '+lstKeys);
As per link : https://salesforce.stackexchange.com/questions/5447/is-there-a-difference-between-an-array-and-a-list-in-apex .
This solution will work.

A quick and simple way to do this would also be:
new List<String>(mmm.keySet());
//or
new String[mmm.keySet()];
In some code I wrote recently I've got a Set<String> and am passing it into a method that takes a List<String> with methodName( new List<String>(setVariable) ); or methodName(new String[setVariable] );
Yes I know the post is 11+ years old... but it is also what comes up when searching so I put my answer here.

Related

How to check if a Map contains a given value in Apex Salesforce?

When raising this question to https://chat.openai.com/chat, this source of info suggests that I can use a method myMap.contains() with the following example:
Map<String, Integer> map = new Map<String, Integer>();
map.put('key1', 1);
map.put('key2', 2);
map.put('key3', 3);
// Check if the map contains the value 2
Boolean containsValue = map.containsValue(2); // returns true
// Check if the map contains the value 4
containsValue = map.containsValue(4); // returns false
But when checking Salesforce soap api for class Map, I do not see any .containsValue() method: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_map.htm#apex_System_Map_methods
So, I think that the AI of https://chat.openai.com/chat might be wrong.
How can I verify, with apex, if a given value is contained in a Map?
Thank you.
Map has a values() method that returns a List containing every value in the map.
If you have to check only one value, you could just call contains() on that list, while if you have to check multiple values you should create a new Set with those values then call contains() (or containsAll()).
Map<String, Integer> myMap = new Map<String, Integer>();
myMap.put('key1', 1);
myMap.put('key2', 2);
myMap.put('key3', 3);
List<Integer> mapValues = myMap.values();
System.debug(mapValues.contains(1)); // true
Set<Integer> mapValueSet = new Set<Integer>(mapValues);
System.debug(mapValueSet.contains(2)); // true
System.debug(mapValueSet.contains(5)); // false
Keep in mind that List.contains() runs in linear time (O(n)) while Set.contains() runs in constant time (O(1)).

JSP array output

How can I get the below output in jsp?
[[1417165200000,28477.92],[1417165320000,28484],[1417165440000,28474.86],[1417165560000,28478.88]]
Both the values comes from a variables in jsp code.
I have tried:
Map<String, String> list = new HashMap<String, String>();
list.put(last_traded_price, price_date);
It gives me this:
{28779.4400=2014-11-28 12:58:00.0, 28794.5000=2014-11-28 01:24:00.0}
Please suggest me what I can use in jsp to get the desired output.
This is what I did in php,
$array_item[] = array(strtotime($price_date)*1000, (float)$last_traded_price);
Update 1:
while(rs.next()){
last_traded_price = rs.getString(1);
price_date = rs.getString(2);
child.add(last_traded_price);//1
child.add(price_date);//2
}
If you want this [[1417165200000,28477.92],[1417165320000,28484]] particular format then i would advice you to use json-simple.jar
so if whenever you want to create data in above format you need to write code as below :
JSONArray root = new JSONArray();
while(rs.next()){
JSONArray child= new JSONArray();
last_traded_price = rs.getString(1);
price_date = rs.getString(2);
child.add(last_traded_price);//1
child.add(price_date);//2
root.add(child);
}
System.out.println(root);
so for 1417165200000,28477.92 this pair you will have root as [[1417165200000,28477.92]]
if you want to add another pair just repeat the steps 1,2 and 3

How to remove a series from DynamicTimeSeriesCollection?

Anyone can guide me on how to remove a series from DynamicTimeSeriesCollection?
In this example, I want to delete series S1
DynamicTimeSeriesCollection dataset = new DynamicTimeSeriesCollection(50, 120, new Second());
dataset.addSeries(gaussianData(), 0, "S1");
dataset.addSeries(gaussianData(), 1, "S2");
I don't know how to do it.
Thank you very much.
DynamicTimeSeriesCollection stores values in an array of ValueSequence. By default a ValueSequence can't be deleted but as ValueSequence is protected you can subclass DynamicTimeSeriesCollection wrtie your own removeSeries method and see if that solves your problem.
Take a look at DynamicTimeSeriesCollection#addSeries and reverse the steps, remember to call fireSeriesChanged() at the end.
Thanks GrahamA for your answer.
Cause i need to touch seriesCount is private, so i must create a new class named DynamicTimeSeriesCollectionModified (copy-paste from DynamicTimeSeriesCollection) and write my own removeSeries and it works.
public void deleteSeries(int seriesNumber) {
//remove item in valueHistory array
List<ValueSequence> listValueHistory = new ArrayList<ValueSequence>(Arrays.asList(valueHistory));
listValueHistory.remove(seriesNumber);
valueHistory = listValueHistory.toArray(valueHistory);
//remove item in seriesKeys array
List<Comparable> listSeriesKeys = new ArrayList<Comparable>(Arrays.asList(seriesKeys));
listSeriesKeys.remove(seriesNumber);
seriesKeys = listSeriesKeys.toArray(seriesKeys);
//update seriesCount
seriesCount--;
fireSeriesChanged();
}

Easiest way to order array from a string word - Interesting

I am writing a childrens game and it consists of letter blocks.
The child has to put the blocks in a correct order (following silhouettes) to spell the word
Now my question is I have 2 Arrays.
var myLetters = new Array(
new BlockC(),
new BlockA(),
new BlockB()
);
public static var myLetters2 = new Array(
new BlockC(),
new BlockA(),
new BlockB()
);
So you see this is setup to spell the word C A B.
What i would would like to do is have a string variable that i can put the word in to and then have code fill the array in the correct order.
i.e.
var word:String = "CAB";
Hope this makes sense and i can get some good help from you guys
Thanks
If I understand the question correctly, here is one way of doing it :
var word:String = "CAB";
var letterClassMapping:Object = {
"C":BlockC,
"A":BlockA,
"B":BlockB
};
var myLetters:Array = [];
for(var i:int=0; i<word.length; i++) {
myLetters.push( new letterClassMapping[word.charAt(i)]() );
}
Another way is to use getDefinitionByName to get the class type :
var classType:Class = getDefinitionByName("Block" + word.charAt(i)) as Class;
myLetters.push(new classType());
You seem to need a letter collection with corresponding classes. So, you make yourself an Object of the following srtructure:
private static var LETTERS:Object={A:BlockA,B:BlockB,C:BlockC};
Then you split your word by single letters (copy one letter out of a word into a new string) and then you can get corresponding class via LETTERS[letter], and a new instance of that class via new LETTERS[letter]();
You can also create toString() functions in Your object and thant join array .
In class create function :
public class BlockA {
public function toString():String {
return "A";
}
}
And than You can join array items :
var arr:Array = [new BlockA , new BlockB , new BlockC];
trace(arr.join(""));
// and compare to Your string:
arr.join("") == word;

NullReferenceException while saving XML File with Linq

I keep getting a NullReferenceException at this line UserRoot.Element("User_ID").Value = User.User_ID.ToString();
What exactly am I doing wrong?
Here's the majority of the code for that method
if (File.Exists(Path2UserDB + User.User_ID.ToString() + ".db") == false)
{
File.Create(Path2UserDB + User.User_ID.ToString() + ".db");
}
XElement UserRoot = new XElement("User");
UserRoot.Element("User_ID").Value = User.User_ID.ToString();
UserRoot.Element("Full_Name").Value = User.Full_Name;
UserRoot.Element("Gender").Value = User.Gender;
UserRoot.Element("BirthDate").Value = User.BirthDate.ToString();
UserRoot.Element("PersonType").Value = User.PersonType.ToString();
UserRoot.Element("Username").Value = User.Username;
UserRoot.Element("Password").Value = User.Password;
UserRoot.Element("Email_adddress").Value = User.Email_Address;
XDocument UserDoc = new XDocument();
UserDoc.Save(Path2UserDB + User.User_ID.ToString() + ".db");
Thanks
I know that saving Usernames and Passwords in plain text is incredibly unsafe, but this is only going to be accessed by one process that I will eventually implement strong security
The Element("User_ID") method returns an existing element named <User_ID>, if any.
Since your XML element is empty, it returns null.
You should create your XML like this:
var userDoc = new XDocument(
new XElement("User",
new XElement("User_ID", User.User_ID),
new XElement("Full_Name", User.Full_Name),
new XElement("Gender", User.Gender),
...
)
);
Alternatively, you can call the Add method to add a node to an existing element.
You are getting this error, because there is no XML element called User_ID under UserRoot to set its value. If you comment it out, you will get the same error on the next line and so on for every other Element, since you haven't added Elements with thos names. To create the tree that you want, try this:
XElement UserRoot =
new XElement("User",
new XElement("User_ID", User.User_ID.ToString()),
new XElement("Full_Name", User.Full_Name),
new XElement("Gender", User.Gender),
new XElement("BirthDate", User.BirthDate.ToString()),
new XElement("PersonType", User.PersonType.ToString()),
new XElement("Username", User.Username),
new XElement("Password", User.Password),
new XElement("Email_adddress", User.Email_Address)
);
The following MSDN link on XML Tree Creation with XElement will be of help.
You want to check if the value is null or empty before running methods on it.
if(!String.IsnullorEmpty(User.User_ID))
UserRoot.Element("User_ID").Value = User.User_ID.ToString();

Resources