Creating arraylist of array - java

I am trying to create an Arraylist which has array of Strings at each index. I have used following code:
ArrayList<String[]> deliveryTimes = new ArrayList<String[]>();
String[] str = new String[times.size()];//times is an Arraylist of string
for(int i=0; i<times.size();i++){
str[i] = times.get(i);
}
deliveryTimes.add(str);
With above code all the elements of str array are added at different index in deliveryTimes arraylist. But I want to add str as array at a index. So it should be like following:
[["a","b","c"],["aa","bb","cc"],["aaa","bbb","ccc"]]
But it is like:
["a","b","c","aa","bb","cc","aaa","bbb","ccc"]

....
String[] first = new String[]{"a", "b", "c"};
String[] second = new String[]{"aa", "bb", "cc"};
String[] third = new String[]{"aaa", "bbb", "ccc"};
addArrays(first, second, third);
...
ArrayList<ArrayList<String>> addArrays(String[]... strings) {
ArrayList<ArrayList<String>> allTimes = new ArrayList<>(strings.length);
for (String[] array : strings) {
allTimes.add(new ArrayList<>(Arrays.asList(array)));
}
return allTimes;
}
allTimes contains: [[a, b, c], [aa, bb, cc], [aaa, bbb, ccc]]

Your deliveryTimes list only contains one String[]. Add multiple String[] to deliveryTimes list.
ArrayList<String[]> deliveryTimes = new ArrayList<String[]>();
String[] one = new String[]{"a", "b", "c"};
String[] two = new String[]{"aa", "bb", "cc"};
String[] three = new String[]{"aaa", "bbb", "ccc"};
deliveryTimes.add(one);
deliveryTimes.add(two);
deliveryTimes.add(three);
for (String[] str : deliveryTimes) {
System.out.println(Arrays.toString(str));
}
Output
[a, b, c]
[aa, bb, cc]
[aaa, bbb, ccc]
You need to split your times list and add them to deliveryTimes List separately.

Related

JAVA - How to add content of CSV specific column to List<String>?

This is my CSV, first line is header, Akt (pan), Mc1-1 and etc. is content.
I need to create a function that extracts content of SearchTerm column and adds it to a List<String>.
I tried it with this piece of code but my next processing requires to have List<String> and not List<String[]>. Is there a way to do that or is there any way i can take parsed List<String[]> and make it into List<String> only containing all the search terms?
public List<String> listAllSearchTerms() throws FileNotFoundException {
CsvParserSettings settings = new CsvParserSettings();
settings.selectIndexes(0);
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader("D:\\Projects\\cstocs-test-dev-bitbucket\\cstocs-test-core\\src\\main\\resources\\data\\searchterm.csv"));
List<String> returnList = new ArrayList<>();
allRows.remove(0);
for (String[] strings : allRows) {
returnList.addAll(Arrays.asList(strings));
}
return returnList;
}
If you know which column SearchTerm is you can replace the for loop with
for (String[] strings : allRows) {
returnList.add(strings[0]); //Assumes it's the first column
}
is there any way i can take parsed List and make it into
List only containing all the search terms?
String[] strArr1 = {"a", "b", "c"};
String[] strArr2 = {"d", "e", "f"};
List<String[]> stringArrList = new ArrayList<>();
stringArrList.add(strArr1);
stringArrList.add(strArr2);
List<String> collect = stringArrList.stream()
.map(arr -> arr[0])
.collect(Collectors.toList());
System.out.println(collect);
output:
[a, d]

Generate String array subset with length <= 5

I've got an array of String in Java. I'd like to generate a List of String arrays that contains all the sets of String with length <=5. For example, if
String[] s1 = {"a", "b", "c", "d"}
I want the result as:
List<String[]> s2 = {{"a"}, {"b"}, {"c"}, {"d"}, {"a", "b"}, {"a", "c"}, {"a", "d"}, {"b", "c"}, {"b", "d"}, {"c", "d"}, {"a", "b", "c"}, ...}
but I can't figure out how I can generate it automatically.
You will need a K-subset algorithm implementation. I'm sure they exist in maths libraries, or you could code your own.
S1 is your set (or alphabet) and s2 is the set of subsets up to length k (5).
You have to write your own generator I guess, or use some library for permutations/combinations, there should be plenty of math libs that can do so. Example of own implementation is here:
https://codereview.stackexchange.com/questions/41510/calculate-all-possible-combinations-of-given-characters
In my opinion example in link is exactly what you need - just change input array and length. Also author puts it in one string, and I see you want to have it in array of arrays, so output also should be changed
I'll give you idea to solve this problem.
Start from an empty output string.One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for k equals to k-1.
Here K is the length in your case 1 to 5.
I used this code:
...
String[] cols = ... //linea in input
Set<String> subSet= new HashSet<String>();
Set<Set<String>> sets = new HashSet<Set<String>>();
//popolo l'insieme - escludo la data
for(int i=1; i<cols.length; i++){
subSet.add(cols[i]);
}
// creo l'insieme delle parti e popolo
sets = powerSet(subSet);
public static Set<Set<String>> powerSet(Set<String> originalSet) {
Set<Set<String>> sets = new HashSet<Set<String>>();
if (originalSet.isEmpty()) {
sets.add(new HashSet<String>());
return sets;
}
List<String> list = new ArrayList<String>(originalSet);
String head = list.get(0);
Set<String> rest = new HashSet<String>(list.subList(1, list.size()));
for (Set<String> set : powerSet(rest)) {
if(set.size() < 5){
Set<String> newSet = new HashSet<String>();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
}
return sets;
}

Copy part of another array in Java

I'm new to Java, and I had a quick question.
I have an array named studentInfo[0] that I created from:String studentInfo[] = line.split(","); I would like to make another array from it's first index.
In other words. I have the array studentInfo that lets say looks like this:
"a,b,c,d,
a1,b1,c1,d1,
a2,b2,d2,c2 etc... "
I want another array that takes all the "a" in my other array. Example: "a,a1,a2 etc..."
How would I do this?
I have tried System.arraycopy(studentInfo, 0, array, 0, studentInfo.length); But doesn't seem to work because it does not just give me the first index.
FYI my code is in a while loop which loops every time it hits a new line. See below:
while ((line = reader.readLine()) != null) {
String studentInfo[] = line.split(",");
String array[] = new String[0];
}
Thank you!
I would do something like.
String[] studentInfoA = new String[50] //You can put the size you want.
for(int i=0; i<studentInfo.length-1; i++){
if(studentInfo[i].substring(0,1).equals("a")){
studentInfoA[i]=studentInfo[i];
}
}
i would recommend Vimsha's answer better but since you are learning i didnt want to make you struggle with collections and such, or at least i wouldnt like you to use them without properly knowing about arrays and loops.
Assuming you have this array,
studentInfo = ["a","b","c","d","a1","b1","c1","d1", "a2","b2","d2","c2"]
and you want another array like
studentInfoWithA = ["a", "a1", "a2"]
then
String studentInfo[] = new String[] { "a", "b", "c", "d", "a1", "b1", "c1", "d1", "a2", "b2", "d2", "c2" };
List<String> newList = new ArrayList<String>();
for (String info : studentInfo) {
if (info.startsWith("a")) {
newList.add(info);
}
}
String[] studentInfoWithA = newList.toArray(new String[0]);
In java 1.8, filtering looks like
String[] result = Arrays.stream(new String[] { "a","b","c","d","a1","b1","c1","d1", "a2","b2","d2","c2" })
.filter(e -> e.startsWith("a"))
.toArray(String[]::new);

Error upon adding an array to List<String[]>

List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
Basically I want an array of {a, b, c} however this isn't working. Do I have to iterate and load each element instead? How would I do this?
My error output looks like this:
[Ljava.lang.String;#3d4b7453
[Ljava.lang.String;#24c21495
Your code works fine, but it looks like you're printing the wrong thing. Do this instead:
for (String[] strs : list) {
System.out.println(Arrays.toString(strs));
}
Printing just an array will give you output like what you're seeing.
Try
List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
System.out.println(Arrays.toString(list.get(0)));
I think you want to print this way: -
List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
System.out.println(Arrays.toString(list.get(0)));
This prints: - [a, b, c]
You could use Arrays.toString() to print elements of an array,
System.out.println(Arrays.toString(list.get(0)));
or alternatively iterate over them:
for(String s : list.get(0)) System.out.println(s);
You can use Arrays.asList()
List<String> list = new ArrayList<String>();
String str = "a b c";
list.addAll(Arrays.asList(str.split(" ")));
To print the result is like:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

How to retrieve data from ArrayList consists of array objects

My arraylist contains String array objects.
How Can I get all values?
My code is below,
String cordinates1c,cordinates2l,cordinates2m;
String[] array1={cordinates1c,cordinates2l,cordinates2m};
String[] array2={cordinates1c,cordinates2l,cordinates2m};
ArrayList alist=new ArrayList();
alist.add(array1);
alist.add(array2);
//retreieving
for(int i=0;i<alist.size();i++)
System.out.println("arrayList="+alist.get(i));
if I try to retrieve like above it gives,
07-12 12:42:09.977: INFO/System.out(743): arrayList=[[Ljava.lang.String;#43e11b28]
How to do that?
Arrays should be printed with the help of Arrays.toString() or Arrays.deepToString().
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws Exception {
String[][] a = {{"a", "b", "c"}, {"d", "e"}};
System.out.println(Arrays.deepToString(a));
}
}
for(int i=0;i<alist.size();i++) {
for (String a : alist.get(i)) {
System.out.println(a);
}
}
You have to iterate over the array of strings, too.
You can iterate over your List and then use Arrays.toString() or Arrays.deepToString() to print array contents
for (String[] eachArray : alist) {
System.out.println("arrayList=" + Arrays.deepToString(eachArray));
}
ArrayList<String[]> l;
for (String[] a : l) {
for (String s : a) {
System.out.println(s);
}
}
Hoping that you are trying to print the string in array1
ArrayList<String> alist= (ArrayList<String>) Arrays.asList(array1);
Now print the data from alist.
also have a look into alist.addAll(collection)
But following snippet will add array1 and array2 object to your ArrayList, So retrieval you will get an array object
alist.add(array1);
alist.add(array2);
Are you looking for something like this ?
String cordinates1c = "1", cordinates2l = "2", cordinates2m = "3";
String[] array1 = {cordinates1c, cordinates2l, cordinates2m};
String[] array2 = {cordinates1c, cordinates2l, cordinates2m};
List<String []> alist=new ArrayList<String []>();
alist.add(array1);
alist.add(array2);
for (String[] strings : alist) {
System.out.println(StringUtils.join(strings));
}
Output:
123
123

Categories

Resources