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));
}
}
Related
I want the Java code for converting an array of strings into an string.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
From Java 8, the simplest way I think is:
String[] array = { "cat", "mouse" };
String delimiter = "";
String result = String.join(delimiter, array);
This way you can choose an arbitrary delimiter.
You could do this, given an array a of primitive type:
StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
result.append( a[i] );
//result.append( optional separator );
}
String mynewstring = result.toString();
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified
array. If the array contains other arrays as elements, the string
representation contains their contents and so on. This method is
designed for converting multidimensional arrays to strings
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
public class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
String newString = Arrays.toString(strArray);
newString = newString.substring(1, newString.length()-1);
System.out.println("New New String: " + newString);
}
}
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
String array[]={"one","two"};
String s="";
for(int i=0;i<array.length;i++)
{
s=s+array[i];
}
System.out.print(s);
Use Apache Commons' StringUtils library's join method.
String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character
//Deduplicate the comma character in the input string
String[] splits = input.split("\\s*,\\s*");
return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
If you know how much elements the array has, a simple way is doing this:
String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3];
I have 2 Arrays.
One Array has Strings, which i look for.
static String[] namesToLookFor = { "NR", "STAFFELNR", "VONDATUM"};
the otherArray has Strings, which i got from a *.csv file.
indexString = indexReader.readLine();
indexArray = indexString.split(";");
My Goal is to system.out.println() the Values which are the indexArray[] and NOT in the namesToLookFor[].
For example:
namesToLookFor = {"NR"};
indexArray = {"HELLO","NR"};
//Any Algorithm here...
So in this case"HELLO" should be printed out, since it is NOT in the namesToLookFor[] Array.
If you are using java8 you can do the following
List<String> list = Arrays.asList(namesToLookFor);
Arrays.stream(indexArray)
.filter(item -> !list.contains(item))
.forEach(System.out::println);
You could iterate over your indexArray and check for each element if its contained in your namesToLookFor Array:
String[] namesToLookFor = {"NR"};
String[] indexArray = {"HELLO","NR"};
List<String> excludedNames = Arrays.asList(namesToLookFor);
for(String s : indexArray) {
if (!excludedNames.contains(s)) {
System.out.println(s);
}
}
Will output only "HELLO".
// Put array into set for better performance
Set<String> namesToFilter = new HashSet<>(Arrays.asList("NR", "STAFFELNR"));
String[] indexArray = indexReader.readLine().split(";");
// Create list with unfiltered values and remove unwanted ones
List<String> resultList = new ArrayList<>(indexArray);
resultList.removeAll(namesToFilter);
// Do with result whatever you want
for (String s : resultList)
System.out.println(s);
With Array you can use contains function but after converting it to be ArrayList, the contains function will check if the ArrayList contains a specific value.
for (int i =0; i<indexArray.length; i++) {
if (!Arrays.asList(namesToLookFor).contains(indexArray[i]))
System.out.println(indexArray[i]);
}
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.
I have on ArrayList which contains data like this: 13-ITEM,14-ITEM,15-ITEMGROUP (with a hyphen (-) as the separator).
I want to split this list into two new ArrayLists:
ArrayList-1 containing the ids: [13,14,15..]
ArrayList-2 containing the Strings: [ITEM,ITEM,ITEMGROUP...]
I am new to Java. Thanks in advance.
You can use String#indexOf(char) to find the index in the String of the separator then use String#substring to extract the sub strings, as next:
List<String> list = Arrays.asList("13-ITEM","14-ITEM","15-ITEMGROUP");
List<String> list1 = new ArrayList<>(list.size());
List<String> list2 = new ArrayList<>(list.size());
for (String s : list) {
int index = s.indexOf('-');
// Add what we have before the separator in list1
list1.add(s.substring(0, index));
// Add what we have after the separator in list2
list2.add(s.substring(index + 1));
}
System.out.printf("List 1 = %s, List 2 = %s%n", list1, list2);
Output:
List 1 = [13, 14, 15], List 2 = [ITEM, ITEM, ITEMGROUP]
Split each entry and add the parts to the different lists. If the texts contain more -s, then use substring.
ArrayList<String> input = ...
List<String> output1 = new ArrayList<>(input.size());
List<String> output2 = new ArrayList<>(input.size());
for(String item:input){
String[] splitted = item.split("-");
output1.add(splitted[0]);
output2.add(splitted[1]);
}
You can use the following code
List<String> list = Arrays.asList("13-ITEM", "14-ITEM", "15-ITEMGROUP");
list.stream().map(p -> p.substring(0, p.indexOf('-'))).forEach(System.out::println);
list.stream().map(p -> p.substring(p.indexOf('-') + 1)).forEach(System.out::println);
If you split your concerns like this (each list is created using different logic), you will have a possibility to encapsulate code further. For example you can add some exception handling.
private static Function<String, String> getFunction() {
return new Function<String, String>() {
#Override
public String apply(String p) {
return p.substring(0, p.indexOf('-'));
}
};
}
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