JSON : Array & Compare - java

I have a set of JSON array :
listSession: [h0y78u93, h0y78u93, h0y78u93, h0y78u93, h0y78u93, 9i88u93, 9i88u93, 9i88u93, 9i88u93, 9i88u93]
I've created the array using the below code:
ArrayList<String> listSession = new ArrayList<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
listSession.add(sessionName);
}
}
May I get your advice or opinion on how am I going to compare the value from each of the attributes in the list. If it is the same, I should it as ONE.
Meaning from the above sample, the count should be only TWO instead of TEN.
Thank You.

You can utilize Arraylist.contains() method like below:
ArrayList<String> listSession = new ArrayList<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
if (!listSession.contains(sessionName)) {
listSession.add(sessionName);
}
}
}
OR
You can use a Set implementation which doesn't allow duplicate values instead of ArrayList. There's no need to compare explicitly.
// initialize
Set sessionsSet = new HashSet();
//add like below
sessionsSet.add(sessionName);
sessionsSet.size() // getting the length which should be what you expect to be 2

I would recommend to use a Set over ArrayList here. You can use ArrayList and check the list whether it contains the element and add it. ArrayList.contains() takes O(n) time because it maintains a dynamic array inside. Where as a HashSet or TreeSet can do that check in O(1) and you also don't have to do that compare yourself.
Set<String> setSession = new HashSet<String>();
for(int u=1; u < k+1; u++) {
String str = Integer.toString(u);
JSONArray arrTime=(JSONArray)mergedJSON2.get(str);
JSONObject objSession;
StringsessionName;
for (Object ro : arrTime) {
objSession = (JSONObject) ro;
sessionName = String.valueOf(objSession.get("sessionID"));
setSession.add(sessionName);
}
}

If you're okay using Java 8, then you can use shorthand implementation like this:
Example:
ArrayList<String> data = new ArrayList<String>(Arrays.asList("A", "A", "A", "B", "B", "B"));
// This will be required if your target SDK < Android N
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
List<String> uniqueData = data.stream().distinct().collect(Collectors.toList()); // Results ["A", "B"]
}

Related

forming new small lists from a combination set of two lists

I have two patterns of lists inside a big list.
[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]
To put in simple words, it is a combination of
[ [pricesList1], [DurationList1], [PricesList2], [DurationList2],... ]
I now want to create a new list with the price and corresponding duration from both lists as a pair from each set. For Example :
[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]
I have tried using List<List<Object>> and List<List<String>>. But no use. How can I do this?
I programed as following, which is wrong :
List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList = new ArrayList<List<String>>();
SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
}
}
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
}
}
Assuming the input list always has an even number of sublists and pairs of sublists have the same size, you can use a for loop iterating over the outer lists's element two by two :
List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
List<String> priceList = outerList.get(i);
List<String> durationsList = outerList.get(i+1);
for (int j=0; j<priceList.size(); j++) {
List<String> newEntry = new ArrayList<>();
newEntry.add(priceList.get(j));
newEntry.add(durationsList.get(j));
result.add(newEntry);
}
}
As commented I suggest defining your own class to store the price and duration rather than using that List<String> newEntry.

Sorting a String list with Integer values in Java

I have a column VALUE in my table that contains:
`M_SYSCONFIG = 200600,2600000,700000600,110000600,150000600`
When I sort this list the result is:
110000600,150000600,110000600,200600,2600000,700000600
However, I need the list to be sorted as follows (treat the strings as integers):
200600,2600000,110000600,150000600,700000600
This is the code I have right now for sorting the list:
JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);
for (int i = 0; i< jsArray.size(); i++) {
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
Collections.sort(data);
I need to obtain the results as strings because after sorting I want to apply the following code:
StringBuilder sbValue = new StringBuilder();
if(ft_other_cn.equals(trasactionType)) {
long limitOtherCimb = limit.getFtOtherCimbLimit();
sbValue.append(limitOtherCimb).append(",");
for(String values:data) {
Long limitSysConfig = null;
try {
limitSysConfig = Long.parseLong(values);
} catch (Exception e) {}
if(limitSysConfig == null) {
continue;
}
if(limitSysConfig > limitOtherCimb) {
continue;
}
sbValue.append(limitSysConfig).append(",");
}
customerLimit.setFtOtherCnLimit(StringUtils.removeEnd(sbValue.toString(), ","));
You need to convert you string values to integers like this and then need to sort.
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
List<Integer> intList = new ArrayList<Integer>();
for(String s : data){
intList.add(Integer.valueOf(s));
}
Collections.sort(intList);
I suggest using biginteger because your numbers seems quite large. It's not the most efficient and optimized solution but yeah it will work
public static List<String> sortData(List<String> data){
List<BigInteger>convertedData=new ArrayList<BigInteger>();
for (String s : data)
{
//System.out.println(s);
convertedData.add(new BigInteger(s));
}
Collections.sort(convertedData);
List<String>sortedData=new ArrayList<String>();
for (BigInteger b : convertedData)
{
sortedData.add(String.valueOf(b));
}
return sortedData;
}
Your code:
JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);
for (int i = 0; i< jsArray.size(); i++) {
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
List<String> sortedData=sortData(data); **<------**
Implement a Comparator like this:
Collections.sort(data, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return new Long(Long.parseLong(o1)).compareTo(Long.parseLong(o2));
}
});
You can take help of streams introduced in java 8.
Just add the below line after creating the List and you would have sorted string list
List<String> data = Arrays.asList(value.split(","));
data=data.stream().mapToLong(Long::parseLong).sorted().mapToObj(String::valueOf).collect(Collectors.toList());
If you very large numbers you can use BigInteger
data=data.stream().map(BigInteger :: new ).sorted().map(String::valueOf).collect(Collectors.toList());
If you are using java 6,7 you would have to use a comparator as mentioned by Taher
Collections.sort(data, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return new Long(Long.parseLong(o1)).compareTo(Long.parseLong(o2));
}
});
If you are not able to change your list, then the simplest way is to build a comparator using Java 8 and use the string values as bigintegers. You do not need to convert your string list to a number list.
List<String> list = Arrays.asList("200600,2600000,700000600,110000600,150000600".split(","));
list.sort(Comparator.comparing(item -> new BigInteger(item)));
System.out.println(list);
The magic happens within
Comparator.comparing(item -> new BigInteger(item))
With this you are constructing a Comparator (which is needed for sorting), that compares all items converted to BigIntegers.
You are sorting the numbers as Strings - as a string, 11 comes before 2. You need to first convert the array of strings to numbers, then sort them as numbers.
With the Streams API you can do that on one line:
String value = ...;
List<Long> data = Arrays.stream(value.split(",")).map(Long::new).sorted()
.collect(Collectors.toList());
Since you need them as Long later, I'm using Long as the numeric type.

how to iterate the json objects in the jsonarray [duplicate]

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

ArrayList<Objects[]> to strings to use in SQL IN statement

I am trying to build a string to pass it as an SQL query within the IN statement.
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
This still prints out the memory locations instead of the actual string
askldnlkasdn[[Ljava.lang.Object;#7bb11784, [Ljava.lang.Object;#33a10788, [Ljava.lang.Object;#7006c658, [Ljava.lang.Object;#34033bd0, [Ljava.lang.Object;#47fd17e3, [Ljava.lang.Object;#7cdbc5d3, [Ljava.lang.Object;#3aa9e816, [Ljava.lang.Object;#17d99928, [Ljava.lang.Object;#3834d63f, [Ljava.lang.Object;#1ae369b7]
I have also tried out
using StringBuilder and StringUtils. But things dont seem to work.
Any inputs as to where the problem is?
you should override method toString in your objects
You can use an SQL specific java Array.
try (PreparedStatement stmt = connection.prepareStatement("... IN (?) ...")) {
Object[] elements = ...
stmt.setArray(1, connection.createArray("TEXT", elements));
stmt.executeUpdate();
}
The problem you have is that you are implicitly using the toString() method of the Object elements inside your ArrayList. By default, that method returns the class and address of the Object. You should override the toString() method in every class you will use inside the list so it returns what you want it to.
This is new code that may help,
// Data of Array of Object for test the Code
Object[] a = new Object[1];
a[0] = "Hello";
Object[] b = new Object[1];
b[0] = "Friend";
Object[] c = new Object[1];
c[0] = "This is";
Object[] d = new Object[1];
d[0] = "Just Test";
// The Array List of objects and the data entry
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
// New List of strings
List<String> strings = new ArrayList<>(arrayList .size());
// The Process of adding the data from array list of objects to the strings
for(int i = 0; i < arrayList.size(); i++){
strings.add((String) arrayList.get(i)[0]);
}
// Just for print the data to console
for(int i = 0 ; i < strings.size(); i++){
System.out.println(strings.get(i));
}
System.out.println("askldnlkasdn "+strings.get(0));
I hope that solve the problem, if not please inform me, you can use it for more than one dimensional array.
You can just save it as String , like this code
ArrayList<String> arrayList = new ArrayList<>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
Or you want it Object for specific purpose?

Swings: storing the selected values from List into an array.

I made a List in java as under:
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList places = new JList(names) ;
Then in order to access the selected values I wrote in valueChanged method :
String[] emailID= places.getSelectedValuesList().toString[];
which is coming out to be incorrect ... Kindly help how should I rewrite this line so as the selected values get stored in array.
If you want to have all selected Items as an Array you can do something like this:
public static void main(String[] args){
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList<String> places = new JList<String>(names) ;
places.setSelectedIndices(new int[]{0,1,2});
String[] emailIDs = places.getSelectedValuesList().toArray(new String[]{});
for(String s : emailIDs){
System.out.println(s);
}
}
Note:
I added <String> to the List, because I assume you always want to have Strings as values. That way you can get the List .toArray() method with a generic output. Else you'd need to get an Object[] (Object Array) and cast the values.
For Storing Selected Items in String Array you can try this
Object[] values = places.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}

Categories

Resources