How to convert long array to string array? - java

I am getting the checked items ids in ListView from List.getCheckedItemIds which returns long array, now how to convert this array to String array ?
long [] long_list = ProcessList.getCheckedItemIds();

String[] string_list = new String[long_list.length];
for(int i = 0; i < long_list.length; i++){
string_list[i] = String.valueOf(long_list[i]);
}

The question may be considered unwarranted a few years ago, but it's worth a new look now considering the recent progress in Java land with regards to the emerging Stream API.
Instead of relying on any third-party API, you can use the built-in Stream API for array operations in Java 1.8 and above.
You can now easily use
String[] yourStringArray = Arrays.stream(yourLongArray).mapToObj(String::valueOf).toArray();
And if your intention is to print yourStringArray, you can then convert it into a string using
String str = Arrays.toString(yourStringArray);
****
Lucky for us, Arrays.toString() operates on all types of arrays, so the whole thing can be simplified to just
String str = Arrays.toString(yourLongArray);
Isn't this cleaner?

You can use org.apache.commons.lang.StringUtils like this:
String[] string_list = StringUtils.join(long_list, ",").split(",");

You can leverage apache's BeanUtils to do Array conversion without doing iteration by yourself like below.
Long[] longArrays= (Long[]) ConvertUtils.convert(stringArrays, Long[].class);

Or with Java 8+,
Object[] array = ...; // or i.e. Long[] array
String[] s = Arrays.stream(array).map(String::valueOf).toArray(String[]::new);

You can make a new String array and pass the values of long array to the string array one by one:
String[] s=new String[long_list.length];
for(int i=0;i<long_list.length;i++)
{
s[i]=String.valueOF(long_list[i]);
}
Sorry for the mistakes. I've updated the code.

Related

How to Sort Numeric Array in JMeter Beanshell

I am new to using Beanshell/Java in my JMeter scripts. I have following code in my JMeter Beanshell Processor.
int count = Integer.parseInt(vars.get("student_id_RegEx_matchNr"));
String delimiter = ",";
StringBuffer sb = new StringBuffer();
for(int i=1;i<=25;i++) {
sb.append(vars.get("student_id_RegEx_" + i));
if (i == count){
break; //to eliminate comma after the array
}else {
sb.append(delimiter);
}
}
vars.putObject("myUnsortedVar",sb.toString());
I get following as output when I run script:
myUnsortedVar=5,6,2,3,1,4
I want it to be sorted numerically like this and also stored in a new variable named "sortedVar".
1,2,3,4,5,6
What code can I use to sort this and also store in a new variable so I can use the sorted array in coming JMeter requests. Thanks for help.
Taking sb.toString() = "5,6,2,3,1,4".
Use String::split() to convert from String to String[].
Use Arrays::sort() to sort the array
Use Arrays.toString() to convert from String[] to String
String[] sortedArray = Arrays.sort(sb.toString().split(","));
vars.putObject("mySortedVar", Arrays.toString(sortedArray));
I suppose that in bean shell you may use the same as in Java. Once you fill StringBuffer, there is not easy way to sort the contents. Therefore I would store the contents first into an intermediate ArrayList<String> (or even better ArrayList<Integer> if you always get numbers), then sort it using Collections.sort, and then use another for cycle to put the list's contents into StringBuffer using the comma delimiter.
You could do something like:
char [] responseCharArray = vars.get("myUnsortedVar").toCharArray();
Arrays.sort(responseCharArray);
String mySortedString = Arrays.toString(responseCharArray);
vars.put("mySortedVar", mySortedString.replaceAll("\\,\\,","").replaceAll(" ",""));
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter
As OndreJM suggested, you need to change your approach. Instead of storing values in StringBuffer, store them in ArrayList and then use Collections.sort to sort it. Following code should work for you.
// create an ArrayList
ArrayList strList = new ArrayList();
for (int i=0;i<25; i++){
strList.add(vars.get("student_id_RegEx_" + String.valueOf(i+1)));
}
// sort this ArrayList
Collections.sort(strList);
// use StringBuilder to build String from ArrayList
StringBuilder builder = new StringBuilder();
for (String id: strList){
builder.append(id);
builder.append(",");
}
builder.deleteCharAt(builder.length()-1);
// finally put in variable using JMeter built in 'vars.put'
// do not use vars.putObject, as you can not send object as request parameter
vars.put("sortedVar", builder.toString());

Java Integer[] to int[] [duplicate]

This question already has answers here:
How can I convert List<Integer> to int[] in Java? [duplicate]
(16 answers)
Closed 8 years ago.
I have a List which I need to convert to an int array (int[])
Currently I am doing this:
List<Integer> filters = new ArrayList<Integer>();
// add some elements to filters
int[] filteres = new int[filters.size()];
for(Integer i=0 ; i<filters.size(); i++)
filteres[i] = filters.toArray(
new Integer[filters.size()])[i].intValue();
I think this looks like a messy workaround and that should be somehow else to do this.
So is there a better way to make such conversion?
This can be simplified using the List.get() from the List interface:
int[] filteres = new int[];
for(int i=0 ; i<filters.size(); i++)
//auto unboxing takes care of converting Integer to int for you, if it's not null.
filteres[i] = filters.get(i);
See How to convert List<Integer> to int[] in Java? (which is a duplicate by all means; see this answer in particular).
However, for sake of discussion, consider this similar alternative and notes.
List<Integer> filters = getFilters();
// Arrays must be created with a size: the original code won't compile.
int[] ints = new int[filters.size()];
// Use an Enhanced For Loop if an index lookup into the source
// is not required; i is merely a result of needing to index the target.
int i = 0;
for(Integer filter : filters) {
// Just use auto unboxing Integer->int; no need for intValue()
ints[i++] = filter;
}
The original code is terrible because filters.toArray(new Integer[filters.size()])[i] creates a new array from the list each loop before the index operation. This makes the complexity O(n^2)+ just for the copy! While this can be fixed by replacing the offending expression with filters.get(i), an indexing operation can be skipped entirely in this case.
Using an enumerable approach similar to shown above (i.e. with an enhanced for loop) has the advantage that it will continue to work efficiently over source collections which are not fast-indexable such as a LinkedList. (Even using the filters.get(i) replacement, a LinkedList source collection would result in a O(n^2) complexity for the transformation - yikes!)
Instead of this:
filteres[i] = filters.toArray(
new Integer[filters.size()])[i].intValue();
You can just retreive the element like this:
filteres[i] = filters.get(i);
int[] filteres = new int[filters.size()];
for(int i =0;i<filters.size();i++){
filteres[i]=filters.get(i);
}

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

How to convert Set<String> to String[]?

I need to get a String[] out of a Set<String>, but I don't know how to do it. The following fails:
Map<String, ?> myMap = gpxlist.getAll();
Set<String> myset = myMap.keySet();
String[] GPXFILES1 = (String[]) myset.toArray(); // Here it fails.
How can I fix it so that it works?
Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.
String[] GPXFILES1 = myset.toArray(String[]::new);
If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.
String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.
String[] GPXFILES1 = myset.toArray(new String[0]);
Java 11
The new default toArray method in Collection interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator as argument and can be used as:
String[] array = set.toArray(String[]::new);
There is already a similar method Collection.toArray(T[]) and this addition means we no longer be able to pass null as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.
Java 8
In Java 8 we can use streams API:
String[] array = set.stream().toArray(String[]::new);
We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator as:
String[] array = set.stream().toArray(n -> new String[n]);
The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.
Use toArray(T[] a) method:
String[] array = set.toArray(new String[0]);
Guava style:
Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);
more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html
In Java 11 we can use Collection.toArray(generator) method. The following code will create a new array of String:
Set<String> set = Set.of("one", "two", "three");
String[] array = set.toArray(String[]::new)
See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)
Set<String> stringSet= new HashSet<>();
String[] s = (String[])stringSet.toArray();
I was facing the same situation.
I begin by declaring the structures I need:
Set<String> myKeysInSet = null;
String[] myArrayOfString = null;
In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :
myKeysInSet = json_any.keySet();
With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:
myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);
This was my first answer in StackOverflow.
Sorry for any error :D

How to convert object array to string array in Java

I use the following code to convert an Object array to a String array :
Object Object_Array[]=new Object[100];
// ... get values in the Object_Array
String String_Array[]=new String[Object_Array.length];
for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();
But I wonder if there is another way to do this, something like :
String_Array=(String[])Object_Array;
But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
What's the correct way to do it ?
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:
Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.
First, let's see what Oracle has to say
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?
List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
Probably, many of you would think that this code is doing the same, but it does not.
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
So tList.toArray is instantiating a Objects and not Strings...
Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following
String tArray[] = tList.toArray(new String[0]);
Hope it is clear enough.
The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:
Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
String apply(Object from){
return from.toString();
}
});
This take you away from using arrays,but I think this would be my prefered way.
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
You can use type-converter.
To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
#Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
For your idea, actually you are approaching the success, but if you do like this should be fine:
for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];
BTW, using the Arrays utility method is quite good and make the code elegant.
Object arr3[]=list1.toArray();
String common[]=new String[arr3.length];
for (int i=0;i<arr3.length;i++)
{
common[i]=(String)arr3[i];
}
Easily change without any headche
Convert any object array to string array
Object drivex[] = {1,2};
for(int i=0; i<drive.length ; i++)
{
Str[i]= drivex[i].toString();
System.out.println(Str[i]);
}

Categories