java get elements inside array but know arrayname in string - java

String[] strsub0={"out","err","in","console()"};
String[] strsub1={"print","println","append","close","flush"};
i want to get array elements and i know the name of the array.but i know aray name in String
int i=0; //this i get through a loop ,so i can't code strsub0 in my code.
String arrayname="strsub"+i; //this is array name i want ,but it is a String.
//so i want get all elements inside array which name is strsub+i ;
//arrayname.length not return strsub0.length but i want it.
for(int z=0;z<arrayname.length;z++){
System.out.println(arrayname[z]);
}

You want an array of arrays.
String[][] strsub={{"out","err","in","console()"},
{"print","println","append","close","flush"};
Then you can get
String[] arr = strsub[i];

You could use a Map whose key is what you want and whose value is the array. Like the following:
Map<String, String[]> map = new HashMap<>(); //(assuming you have Java 7+ for the <> operator)
map.put("strsub0 ", new String[]{"out", "err", "in", "console()"});
map.put("strsub1 ", new String[]{"print", "println", "append", "close", "flush"});
Then retrieve the values like: map.get(arrayname)[i]. Of course you would have to check whether map.get(arrayname) actually exists or is null

Related

Converting List<List<String>> to array

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++;
}

Splitting by Tabs in Java

I have a file scanned line by line into an ArrayList.
I then create a new ArrayList in which I want to temporarily store that line into so that I may access certain values.
Ex. IDname(tab)IDnumber(tab)vote(tab)date
So, I create the temporary ArrayList named voteSubmission, and I go through every String in the fileRead array.
Why is it that I get the error incompatible type for my split method?
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
voteSubmission = x.split("\t");
}
The split method returns an array, not an ArrayList.
Either work with an array or convert it to an ArrayList manually.
x.split("\t"); this function will return an array not array list
The split function states that:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Returns:
the array of strings computed by splitting this string around matches
of the given regular expression
You may try to change your code like this:
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
for(String value: x.split("\t"))
{
voteSubmission.add(value);
}
}
The output of split() is of type string[] array and you are trying to assign to an ArrayList type, which is incompatible.
Change your code to
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
String arr[] = x.split("\t");
if(arr != null && arr.length > 0)
{
for(String value: arr)
{
voteSubmission.add(value);
}
}
}
The error is: Type mismatch: cannot convert from String[] to ArrayList<String>
Which means that x.split("\t") provides a String[] array, but you assign it to an ArrayList.
If you'd like it to be an ArrayList, you'd have to convert it like this:
new ArrayList<String>(Arrays.asList(x.split("\t")));
But since you are doing this in a loop it is likely that you would like to store all Arrays within the ArrayList. To do this, you have to create an ArrayList of type String[], like this:
ArrayList<String[]> voteSubmission = new ArrayList<String[]>();
for(String x : fileRead){
voteSubmission.add((x.split("\t")));
}

how to get just one item from array of strings if the other is the same

I want to know if there is a function in Java retrieve one string from array of strings if the other strings are the same i.e. if I have in my array :
yes,yes,yes,yes,no,no,no,no .. I want to get only one yes and one no and display them!
and not by using for loop and comparing ! , just I want to know if this function exists in Java .
Insert all those into a Set.Then u will get like that
String[] array = {"yes","yes","yes","yes","no","no","no","no"};
Set<String> mySet = new HashSet<String>(Arrays.asList(array));
Set does not allow duplicates.
Finally the set contains yes and no(only 2 elements)
If this is your array
String[] a = {"yes","yes","yes","yes","no","no","no","no"};
then this will display unique values
System.out.println(new HashSet(Arrays.asList(a)));
Dump your array into a set and use that:
Set uniqueStrings = new HashSet(Arrays.asList(yourArray));
If you need it as array again you can use
String[] uniqueStringsArray = uniqueStrings.toArray(new String[uniqueStrings.size()]);
Internally, this iterates through the array and compares the Strings. You cannot avoid that.
Try some thing like this
String[] arr=new String[]{"yes","yes","yes","yes","no","no","no","no"};
Object[] unique = new HashSet<>(Arrays.asList(arr)).toArray();
System.out.println(unique[0]);
System.out.println(unique[1]);

Referring a variable with a variable in java

I have got into a strange strange situation. I have 3 sets of strings like this
String set1q1="something"; //associated with randomNum=1
String set1q2="something";
String set1q3="something";
String set1q4="something";
... and so on
String set2q1="something"; //randomNum=2
String set2q2="something";
String set2q3="something";
String set2q4="something";
... and so on
String set3q1="something"; //randomNum=3
String set3q2="something";
String set3q3="something";
String set3q4="something";
... and so on
All these strings are initialised only once. Now in my program i generate a random number between 1-3. I converted this random number into a string and stored it into a string called set.
String set=randomNum.toString();
Now next intead of using "if-else" to send the data(if randomnum=1 send set1q1-5, if randomnum=2 then send set2q1-5), I want the appropriate data to be sent using one line.
For example: if random no 2 is chosen then set2q1 has to be sent where the "2" in between is has to be the value of "set"(which is defined above).
set"set"q1 //where set can be 1,2,3
Is there any way to do this?
What you are asking for is not possible;1 it's just not the way Java works. Why don't you just use an array, or a collection?
List<List<String>> allTheStrings = new ArrayList<List<String>>();
List<String> myStrings = null;
// Add a subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
// Add another subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
...
// Obtain one of the strings
String str = allTheStrings.get(1).get(2);
1. Except in the case where these variables are members of a class, in which case you could use reflection. But really, don't.
It is not possible. Local variable identifiers are converted to numbers (stack offsets) during compilation. But you should use arrays or collections anyway
Sounds like you want to index Strings by two indices. You should use a two-dimensional String array: String[][] strings. You may then access the desired string with strings[n][m]
Or you can achieve the same effect with a List<List<String>> strings if you need the dimensions of your 2D array to grow dynamically. You'd access the value you need with strings.get(n).get(m)
If you really want to access your strings by a composed name such as set2q1, then you just need a Map<String, String> strings. Then you'd access each value with strings.get("set" + m + "q" + n)
looks to me you should look into arrays, like this:
String[] strings = new String[]{"xxx", "yyy", "zzz"};
String string = strings[randomNumber];
create an arraylist instead and reference using the list index

String selection and assigning

String a="aaa";
String b="bbb";
String c="ccc";
String d="ddd";
String p,q,r,s;
How can I assign values to p,q,r,s
randomly from a,b,c,d?
Like p should have value from a,b,c,d
and similarly for q,r,s
But the value should not repeat.
The easiest way to do it is probably to just put all the strings in a array (or list, or similar), shuffle the list and assign the first value in the shuffled array to p, the second to q, etc.
Here's an example of how to do this:
String[] strings = new String[] {
"aaa", "bbb", "ccc", "ddd"
};
Collections.shuffle(Arrays.asList(strings));
String p = strings[0],
q = strings[1],
r = strings[2],
s = strings[3];
Create an array of a,b,c,d, and use a random 0~3 index to get the value.
Add your Strings to a List<String> and then use java.util.Random class's nextInt(sizeOfList) method.

Categories

Resources