I want to randomize or shuffle the order of the string array using the code below
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[]=str;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<str.length; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<str.length; i++) {
strTmp[i]=str[list.get(i)];
System.out.println(strTmp[i]);
}
}
The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...
You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line
String strTmp[] = str;
to
String strTmp[] = new String[str.length];
If you don't want to change the array str. Try this.
String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));
output
[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]
When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.
You may just do
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
Collections.shuffle(Arrays.asList(str));
This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.
If you require a new array with the shuffled strings and the old array unmodified, the solution is:
List<String> list = new ArrayList<>(Arrays.asList(str));
Collections.shuffle(list);
String[] newStr = list.toArray(new String[0]);
System.out.println("Original array: " + Arrays.toString(str));
System.out.println("New shuffled array: " + Arrays.toString(newStr));
Edit: Output from one example run:
Original array: [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]
As you can see, the original array is unmodified.
Edit: Since Java 11 it’s nicer to create the new array using Collection.toArray(IntFunction<String[]>):
String[] newStr = list.toArray(String[]::new);
See both code snippets run live in IdeOne.
I understand that you want to randomized your array in every execute. Here is the code for this.
import java.util.*;
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
List<String> list =Arrays.asList(str);
Collections.shuffle(list);
System.out.println(list);
}
Related
I have elements that is declared in a list variable such as:
List<List<String>> textList = new ArrayList<>();
The elements are added such as:
textList.add(Arrays.asList(p)); //adding elements
The only way I could output the elements inside the variable is by using:
for(List<String> s: textList){
System.out.println(s); }
which output elements like this:
[He is a boy.]
[He likes apple.]
[She is a girl.]
Now, I would like to store them in an array so that the elements will look like this when outputted.
[He is a boy., He likes apple., She is a girl.]
I've tried
String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);
for(String s : textArr){
System.out.println(s);}
but I got an error about:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
So, how do I convert the elements inside a list into array using the proper way. Thanks!
Your problem is that you are not storing Strings in your list textList.
textList.add(Arrays.asList(p));
As the type says, you have a List of List of String here.
So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!
But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.
What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:
for (String someString : someCollection) {
System.out.println(someString);
}
someCollection can be both: array or List!
In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.
Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).
(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).
Using streams and flatMap, you can do this:
List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);
This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):
List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);
You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like
//Your list
List<List<String>> textList = new ArrayList<>();
//The iterators
Iterator<List<String>> itList = textList.iterator();
Iterator<String> itString;
//The string to store the phrases
String s[] = new String[textList.size()];
int i =0;
//First loop, this seeks on every list of lists
while(itList.hasNext()){
//Getting the iterator of strings
itString = itList.next().iterator();
s[i] = "";
//2nd loop, it seeks on every List of string
while(itString.hasNext()){
s[i] = s[i].concat(itString.next());
}
s[i] = s[i].concat(".");
i++;
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
What I am trying to do is add an array to an arraylist. I've looked at other examples that tell me to do what I am doing, but I get nonsense output when I run the program. I would also like to access certain elements of an array within the arraylist, and I have no idea how to do that.
static int elements = 10; //Or whatever number you'd like
public static void main(String[] args)
{
int[] person = new int[4];
ArrayList personID = new ArrayList();
experiment(personID, person);
}
private static void experiment(ArrayList personID, int[] person)
{
for(int i = 0; i < elements; i++)
{
person[0] = i;
person[1] = i;
person[2] = i;
person[3] = i;
personID.add(person);
}
System.out.print(personID);
}
Output:
[[I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87]
Not that much of an explanation is needed, but I declare the array and arraylist, pass them to a function which keeps giving the array's elements different values and then, supposedly, adding the array itself to the arraylist for each iteration.
The output, though, it nothing like what I am looking for. I could do another loop to print each array element for each spot along the array list, but I don't know how to do that. I figured
System.out.print(personID.get(i[0]);
Or
System.out.print(personID.get(i)[0];
But it doesn't work and I'm lost...
Thank you for dealing with me!
It's just a problem with the way you're printing the arrays. Try this instead:
for (int[] a : personID)
System.out.println(Arrays.toString(a));
Not only are you attempting to print arrays by implicitly invoking toString, but also adding the same array over and over to the list. The variable called person is a reference to an array object. You keep changing its elements and adding the same reference.
Were your print routine to be correct, the output would only show an array of four 10s repeated 10 times.
Arrays doesn't implement its own toString() implementation it uses Object#toString() and that is why you are watching that output
getClass().getName() + '#' + Integer.toHexString(hashCode())
[I means that is an Integer array plus # followed with it's hashcode e1cba87.
One way to solve it is using Arrays.toString()
For example:
public static void main(String[] args){
int[] person = new int[4];
List<int[]> personID = new ArrayList<>();
experiment(personID, person);
//now print
for(int[] array : personID){
System.out.println(Arrays.toString(array));
}
}
is it possible to run the following code with logic in 6th line ?
public class arraylist{
public static void main(String args{}){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible?
}
Iterator it=al1.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
Change al.add(s); by al.addAll(Arrays.asList(s)); and you should be all set.
Try the following:
ArrayList<String> al = new ArrayList<String>(Arrays.asList(s));
You have the answer in your question.
When you say you want to convert array asList
As many have already suggested, use Arrays.asList. But before the code would work, you would still need to fix the formatting as you have code outside the main method that is referring to your array list variable in the main method.
public static void main(String[] args){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(Arrays.asList(s));
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible ?
Yes. It is possible.You can add any object to ArrayList including array object.
But while iterating the ArrayList object you will get an array element by calling it.next().So output will be String representation of array object not the array elements
So try this
String s[]={"Sam","Tom","Jerry"};
ArrayList<String> al=Arrays.asList(s);
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
I did the following to store arrays in a ArrayList. The declaration is:
ArrayList<String[]> training = new ArrayList<String[]>();
To input the words and add it:
String input = sc.nextLine();
s1 = input.split(" ");
training.add(s1);
The split method splits the string with spaces and stores each word in the respective index in array s1 which was already declared with the size required for the program."sc" is the scanner object already declared.The individual arrays can be accessed by using:
String s4[] = training.get(index_of_array_you_want);
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList arr=new ArrayList(Arrays.asList(array))
I am trying to create a method to takes an array of names and returns a copy of the list with the names randomly rearranged. The code below returns a new list with duplicated names. what can I do to shuffle names of the new list instead?
public static String[] shuffle(String []names)
{
int num =0;
String [] newArray = new String [names.length];
Random r = new Random ();
for(int i = 0; i<names.length; i++){
num = r.nextInt(names.length);
if((i-1)!=num){
newArray[i]=names[num];
}
}
return newArray;
}
You can use Collections.shuffle() to shuffle a list.
If you are eager to do it by your own - have a look on fisher-yates shuffle.
(Pseudo code:)
for (i = n-1; i >= 0; i--)
swap(names,i,r.nextInt(i+1));
(Where swap() is a standard swapping function to swap two elements in an array)
(Note, if you want a new instance with the shuffled array - just copy it using Arrays.copyOf() before running the algorithm.
Like others have suggested there are already other cleaver/easy ways to do this, but to solve the issue in your code you need to make the newArray a copy of the names array (you can can use Arrays.copyOf) and then properly swap the values, like:
if(i!=num){
String aux=newArray[i];
newArray[i]=newArray[num];
newArray[num]=aux;
}
Collections.shuffle(list)
Info
You can use the ToList to make it a list for the shuffle and then back to an array with ToArray.
This may not be the most efficient but it is the easiest.
public String[] shuffle(String[] ss) {
List<String> list = Collections.shuffle(Arrays.asList(ss));
return list.toArray(new String[ss.length]);
}
In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}