This question already has answers here:
How to convert Set<String> to String[]?
(7 answers)
Closed 4 years ago.
I'm trying to convert my set of Strings to an array of Strings so I can operate on them one by one. Is there a better way of doing this or is converting to arrays a good way? However, when I try converting to an array like below then I get errors as it doesn't think that it will always be strings passed in. Would appreciate some pointers.
Set<String> s;
s.add("a");
s.add("b");
String[] item = s.toArray();
You do not have to convert a Set to an array just to operate on the elements. You can iterate over the elements directly
Set<String> s = new HashSet<>();
....
for (String item : s)
{
do something...
}
so I can operate on them one by one
You don't have to convert it to an array for that.
Instead iterate using the for-each loop or the iterator.
you can do something like this
String[] item = s.toArray(new String[s.size()]);
As per Java doc - toArray function ( which is the one you need )
toArray() Returns an array containing all of the elements in this list
in proper sequence (from first to last element).
Related
This question already has answers here:
Sorting ArrayList by specific value
(4 answers)
Closed 8 months ago.
I want to sort a ArrayList of Strings (descending order) which are in the following format : "row,column".
But since I can't find a way to do that, I thought of converting the ArrayList of Strings into ArrayList<ArrayList> and sorting it in descending order.
For e.g.,
the strings : "21,10", "19,25", "32,5"
will be converted into an ArrayList<ArrayList> like so: [[32,5],[21,10],[19,25]].
NOTE : I only want to sort in descending order based on the first index of inner ArrayList.
This is how you can achieve it with an Arraylist of strings.
ArrayList<String> list = new ArrayList<String>();
list.add("21,10");
list.add("19,25");
list.add("32,5");
Once you have your list, you can simply use Collections.sort() method.
Collections.sort(list);
For reverse order simply add another argument to the sort method.
Collections.sort(list, Collections.reverseOrder());
Print the list to verify.
System.out.println(list);
Here is a running code example.
https://onecompiler.com/java/3y7ahcm6x
I have this string:
string1="A.1,B.2,C.4"
I want to get the following arraylist of arraylist:
<<"A","1">,<"B","2">,<"c","4">>
is there any way other than using for loop?
suppose that arraylists are unique, so I would have
Set<String> set= new HashSet<>(Arrays.asList(string1.split(",")));
now I want to split each element in the above set on ., without using for loop.
I was thinking of first splitting based on ,. Then, split each of those on ., put both values in a list, and then put that list in another list. Something pseudo-code-y that should work. :)
string1="A.1,B.2,C.4"
stringsWithDots[] = string1.split(",");
List<List<String>> result = new ArrayList<List<String>>();
for(String stringWithDots: stringsWithDots) {
finalSplit[] = stringWithDots.split(".");
List<String> list1 = Arrays.asList(finalSplit);
result.add(list1);
}
"A.1,B.2,C.4" would look like [[A,1],[B,2],[C,4]]
Edit.
[asList source]
[split] which is used to split a string [has a loop].
ArrayList is backed by an array. The asList function simply sets a reference to that array [source].
So, that thing you say about not using a loop. Well, be it using stream or some internal function, loops happen; just that you might not be seeing it in the immediate code that you write.
This question already has answers here:
Take n random elements from a List<E>?
(12 answers)
Closed 8 years ago.
I am using Java and I am using a vector 'set' to store data
This is created from a text file as I read each line and store it in an array values[]. Then I have a vector 'set' and for each line I add values[] to the vector 'set' so set looks as shown as above after all the data from the text file is read.
Then the user is given a choice to input the amount of data he wants, for example if he enters 50, half of the vector (the first 7 lines) would be taken by using:
public void pro(int percentage)
{
int noOfEx = percentage*set.size()/100;
root.keptEx = new Vector(set.subList(0, noOfEx));
}
However, I wish that the lines are taken randomly and not after each other but I cannot figure out how to do it with random. Also is there a way how to print out the values of the vector? since
System.out.println(keptEx)
displays weird symbols not the actual contents.
Shuffle the list of rows:
Collections.shuffle(list);
Then take the first N rows of the shuffled list. Note that calling set what is in fact a list is not a very good idea. Also note that Vector shouldn't be used anymore since Java 2, and we're at Java 8. Use an ArrayList instead. And use generic types, not raw types. These exist since Java 5.
The easiest way to print your list would be to make it contain lists instead of arrays (i.e. you would jave a List<List<Integer>> instead of a List<int[]> (assuming that's what you have). If you want to keep using arrays, then you'll have to loop over each element of your list:
for (int[] row : list) {
System.out.println(Arrays.toString(row));
}
This question already has answers here:
How to add new elements to an array?
(19 answers)
How can I dynamically add items to a Java array?
(11 answers)
Closed 8 years ago.
I have an array, defined as below:
String[] letters = {"ab", "cd", "ef", "gh"};
How would I go about adding an item to this array?
1.Arrays are fixed in size
2.Before declaring an array we should know the size in advance.
3.We cannot add anything dynamically to an array once we declare its size.
I recommend you to go for collection framework like List or Set where you can increase the size dynamically
By using this type of array initialization you cannot simply add more elements.
String[] letters = {"ab", "cd", "ef", "gh"};
Could be paraphrased as:
String[] letters = new String[4];
letters[0] = "ab";
letters[1] = "cd";
letters[2] = "ef";
letters[3] = "gh";
So, your array's length is only 4.
To add more elements you should somehow copy you array to a bigger one and add elements there. Or just use ArrayList which does the hard work for you when capacity is exceeded.
Java arrays having static size. One you define the size of a array, it can't grow further dynamically.
Your letters array has a size of 4 element. So, you can't add more element to it.
Use ArrayList instead
List<String> letters = new ArrayList(); // Java 7 and upper versions
letters.add("ab");
letters.add("cd");
....// You can add more elements here
This is not possible without a workaround
like http://www.mkyong.com/java/java-append-values-into-an-object-array/
try ArrayList, List, Map, HashMap or something like this instead
This question already has answers here:
Randomly select an item from a list
(5 answers)
Closed 4 years ago.
I am using java.util.LinkedList
Is there any method that helps me with this?
int len = list.size();
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(len);
If you only need one element you can use the Random class to generate a (pseudo) random value (as you wrote in your question):
E element = list.get(new Random().nextInt(list.size()));
Remember LinkedList.get(index) is an O(n) operation, as noted in the comments it's better to use an ArrayList for this purpose.
If you want to shuffle the whole array you can use the Collections api like this:
Collections.shuffle(list);
You can also shuffle the List using Collections.shuffle and pick the first element everytime though this might be a bit expensive computation wise. Just another trick you should be aware of. :-)
final List<String> lst = Arrays.asList("a", "b", "c");
Collections.shuffle(lst);
final String rndStr = lst.get(0);
Get the list length with size(), create a random number between 0 and size-1 and use get(index) to retrieve the element with that index.
If you really need just one element, go with dacwe's solution. If you need several values (e.g. when simulating a card game, bingo etc.) you can use java.util.Collections.shuffle(list);, and call list.remove(0); for every element you need.