If I have an observableList data1 = FXCollections.observableArrayList();
I want to stick it in an array because I have a bunch of them.
Can I do that ?
If yes, whats the syntax ?
List interface provides a method called toArray() to convert a list to array. This should do:
data1.toArray();
EDIT
As per the questioner input, you may need this:
observableList[] observableListArray = new observableList[SIZE_YOU_NEED];
observableListArray[index] = data1;
Related
I have an ArrayList (~900 entries) containing arrays of user information:
[swaschit, Sophia Waschitz, Dormant, Inactive, 1/1/2018]
[kolanday, Kyle Olanday, Dormant, Inactive, 1/1/2018]
[npowers, Neil Powers, Assigned, Active, 2/11/2018]
I want to generate an array from this list containing only the first elements of each object:
[swaschit, kolanday, npowers, ...]
What is the most efficient way of doing this?
One way is to use a Stream and map each of the inner arrays to its first element:
List<String> firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.collect(Collectors.toList());
If you would like an array of strings instead:
String[] firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.toArray(String[]::new);
I also suggest you to not use nested arrays like this. You should create a class with the properties you want to store and create a List of your class.
As I suppose the first entry is unique (as it seems to be a username), I would suggest using a Map. That way, you could simply list the keys.
HashMap<String,ArrayList<String>> hashmap=new HashMap<>();
Alternatively, you could simply create a class containing that information, to avoid needing the use of an ArrayList, but I don't know if this is an option.
As pointed out using an appropriately designed Object rather than an array of such heterogeneous data (guessing they are Strings in reality).
If you insist on keeping it the way you have though, you just need to allocate a new array with the size of the original ArrayList and iterate through, fetching the desired column. Assuming ArrayList<String[]> list
int size = list.size();
String[] firstColumn = new String[size];
for (int i = 0; i < list.size(); i++) {
firstColumn[i] = list.get(i)[0];
}
I suppose that you can do
list.stream().map(array -> array[0].toString()).toArray()
I have an custom class InfoAQ which has a method called public String getSeqInf(). Now I have an ArrayList<InfoAQ> infList and
I need an ArrayList<String>strList = new ArrayList<String>with the content from getSeqInf()for each element.
This is the way Im doing it right now ...
for(InfoAQ currentInf : infList)
strList.add(currentInf.getSeqInf());
Is there an alternative way to make it ? Maybe a faster one or one liner ?
Yes, there is:
strList = infList.stream().map(e -> g.getSeqInf()).collect(Collectors.toList());
The map step can be also written in another way:
strList = infList.stream().map(InfoAQ::getSeqInf).collect(Collectors.toList());
which is know as method reference passing. Those two solutions are equivalent.
Also maybe this one:
List<String> strList = new ArrayList<String>();
infList.forEach(e -> strList.add(e.getSeqInf()));
And there is another one (-liner, if you format it in a single line):
infList.forEach(currentInf -> {strList.add(currentInf.getSeqInf());});
while I would prefer a formatting in more lines:
infList.forEach(currentInf -> {
strList.add(currentInf.getSeqInf());
});
Using streams
infList.stream()
.map(InfoAQ::getSeqInf)
.collect(Collectors.toCollection(ArrayList::new))
Using Collectors.toCollection here to create an ArrayList that will hold the results as you do in your case. (Important if you do care about the result list type as Collectors.toList() does not guarantee this)
May not be the fastest as using stream has some overhead. You need to measure/benchmark to find out its performance
This code will iterate all the data in the list, as getSeqInf returns a String, the collect method will store all returns of the getSeqInf method in a list.
`List listString = infList.stream().map(InfoAQ::getSeqInf).collect(Collectors.toList());`
or
`
ArrayList<String> listString = new ArrayList<>();
for(int i = 0; i < infoAq.size(); i++) {
listString.add(infoAq.get(i).getSeqInf());
}`
I have a method that takes vararg Array of strings
void count(long delta, String... tags);
I have a predefined array of tags for the most cases
String[] tags = { "foo_tag:Foo",
"bar_tag:Bar",
"baz_tag:Baz"
};
and only one tag to be added to predefined tags in each call "project_id:12345"
So the call of count should look like this:
count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");
How can I simply create a new array containing my existing one plus additional element just in place of calling the method?
Something like this hypothetical Arrays.append method:
count(delta, Arrays.append(tags, "project_id:12345"));
This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.
Currently, I have helper method appendTag, but it doesn't look elegant as for me
private String[] appendTag(String[] tags, String s)
{
String[] result = new String[tags.length + 1];
System.arraycopy(tags, 0, result, 0, tags.length);
result[result.length-1] = s;
return result;
}
In java, arrays have a fixed size so it won't be possible to extend an array by appending new elements to it.
You will need to create a new array with a larger size and copy the first one elements into it, then add new elements to it, but it's not dynamic yet.
What I can suggest is to use a Collection maybe an ArrayList you will profit from its built-in methods like .add()
There is no easy way to expand an array by one element and add something new. But if you were working with a list instead, you could easily add a new element and then convert it to an array when calling the method:
String[] tags = { "foo_tag:Foo",
"bar_tag:Bar",
"baz_tag:Baz"
};
List<String> tagList = new ArrayList<String>(Arrays.asList(tags));
tagList.add("project_id:12345");
count(delta, tagList.toArray(new String[0]));
If you think you will have a long term need for this, then perhaps consider changing the implementation of count() to use a list instead of an array. You could also overload this method and expose a version which accepts list instead of array.
I have an ArrayList which stores 100 instances of a POJO named Funds. Here is what Funds looks like:
public class Funds
{
private String InvestmentName;
private String PrimaryInvestmentObjective;
private String AgencyOrMissionRelatedNeeds;
}
here is what my ArrayList looks like: ArrayList<Funds>
I need to get a complete list of InvestmentName from fundList, and I need to store all 100 InvestmentNames in an array. I tried to look to see if ArrayList had some kind of filter but couldn't find any.
please you can use java 8 stream api like
List<String> names= funds.stream().map(Funds:InvestmentName).collect(Collectors.toList());
please note this code is not test but it should work fine
It looks like you need to write a get method for your InvestmentName member and you also need to write a method that iterates through the ArrayList and puts each InvestmentName into an array.
So you have an ArrayList<Funds> and you want to transform that into an ArrayList<String> or String[] of investment names, is that right?
Have you tried something like this?
ArrayList<String> investmentNames = new ArrayList<>();
for (Funds f : fundsList) {
investmentNames.add(f.getInvestmentName());
}
If you really want to convert the result into an array (String[]) afterwards you would call this:
String[] investmentNamesArray = investmentNames.toArray(new String[investmentNames.size()]);
However you should avoid mixing arrays and Lists (Effective Java Item 25: Prefer lists to arrays) and just use investmentNames directly.
I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.