I have
String add_data[] = new String[6];
with datas at 0,1,2,3,4,5 indexes.
Also I have
ArrayList<String> data = new ArrayList<String>();
now I need to put the values in all the indexes in add_data at data[0].
How can i do this? please guide me.
Eg. add_data[0]="a";
add_data[0]="b";
data[0] should have "ab"
use Arrays.asList(array) method to copy array to List. In your case - String[] to List<String>.
String result = "";
for (int i = 0; i < add_data.length: i++) {
result += add_data[i];
}
data.add(result);
I'm not sure to understand what you want to do, but try this :
String temp = "";
for(String s : add_data) {
temp += s;
}
data.put(temp);
You need:
Catenate all Strings from your array
Put this at 0 index in your ArrayList
Something like this:
String addData[] = new String[6];
ArrayList<String> data = new ArrayList<String>();
addData[0] = "a";
addData[1] = "b";
// 1. catenate all strings
String str = "";
for (String s : addData) {
str += (s != null)?s:"";
}
// 2. put it into 0 index in your arraylist
data.add(0, str);
System.out.println(data.get(0));
Related
I have a text string that I receive from PL/SQL. I need to convert each object that is separated by a ';'.
This is my string enter image description here
I need to get that information and create the objects that come in that string.
//all objects come in a single text string
first object is 830114921-1<,>TIGO<,>13<,>RECARGA CELULAR TIGO;
second object is 800153993-7<,>PROTOCOLO CLARO<,>426<,>PAQUECLARO 24HRS;
third object is 800153993-7<,>PROTOCOLO CLARO<,>7<,>PINES 2000;
fourth object is 900102005-1<,>GLOBAL TV TELECOMUNICACIONES<,>92<,>JOHATRUJILLO;
Example:
Class MyClass{
Integer number;
String text;
Integer number2;
String text;
}
List<MyClass> myList = new ArrayList<>();
myClass.SetNumber(830114921-1);
myClass.SetText("TIGO");
myClass.SetNumber2(13);
myClass.SetText2("RECARGA CELULAR TIGO");
myList.add(myClass);
//I can split the 4 objects but if more objects come in the text string, can //no longer be.
String str = "830114921-1<,>TIGO<,>13<,>RECARGA CELULAR TIGO;"
+ " 800153993-7<,>PROTOCOLO CLARO<,>426<,>PAQUECLARO 24HRS; "
+ "800153993-7<,>PROTOCOLO CLARO<,>7<,>PINES 2000; "
+ "900102005-1<,>GLOBAL TV TELECOMUNICACIONES<,>92<,>JOHATRUJILLO;";
String[] arrOfStr = str.split(";", 4);
List<String> list = new ArrayList<>();
for (String a : arrOfStr) {
list.add(a);
}
for (String data : list) {
String result2 = data.replaceAll("\\<,>", " ");
System.out.println(result2);
}
You can count how many ; exits in the String and then use str.split()
...
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ';') {
count++;
}
}
String[] arrOfStr = str.split(";", count);// instead of 4
...
This will solve you problem but there are better ways to do it, using a regular expression . Learn more here
Edit :
You also need to do the same thing to every attribute of your object but the counting is a little bit different :
...
count = 0;
for (int i = 1; i < arrOfStr[0].length()-1; i++) {
if (arrOfStr.charAt(i-1) == '<'arrOfStr.charAt(i) == ',' && arrOfStr.charAt(i+1) == '>') {
count++;
}
}
List<String> listOfObjectsFromSQL = new ArrayList<MyClass>();
String[] attributes = new String[count];
for (String strObj : arrOfStr) {
attributes = strObj.split("<,>", count);
//create you object
MyClass obj = new MyClass();
//fill your object with values from the query
obj.setNumber(attributes[0]);
obj.setText(attributes[1]);
obj.setNumber2(attributes[2]);
obj.setText2(attributes[3]);
//add them to your list to use them...
listOfObjectsFromSQL.add(obj);
}
...
The data is split with <,> and ; so you should easily be able to split the string and collect the data. Java has a String.split() method. First split the string object that contains all the data into an array of strings by splitting on ; and then loop over these and split them on <,>.
At this point you should be able to set your attributes according to the order of the data in the string (assuming these are ordered properly).
just after a bit of help with something that I cant seem to get right.
I have the following code which displays the values in a csv file. This is working.
while(file.hasNext()){
String data = file.nextLine();
String[] values = data.split(",");
for(String index : values){
System.out.printf("%s \t", index);
}
System.out.println();
}
The code displays:
1 John Smith Engineering
2 Jim Jones Cooking
I want to take the values just from values[0] (which are the ID's - 1,2) and copy them into a new int array so I can pass this to other methods to perform searches and whatnot. Any help would be greatly appreciated.
Thanks!
Not quite sure I understand your question fully, but you can try this:
String[] str_array = {...};
int[] int_array = {...};
int_array[index] = Integer.parseInt(str_array[index]);
This way you can add a String to an int array, watch out for NumberFormatExceptions.
Edit:
ArrayList<Integer> ids = new ArrayList<>(); // IDs: 1, 43, 23...
Scanner scanner = new Scanner(System.in); // Reading from console
int input = scanner.nextInt();
if (ids.contains(input)) {
// true
} else {
// false
}
Just save values[0] into a seperate list and convert it to an array. If you know the number of ids you can directly save your ids into an array.
List<String> ids = new ArrayList<>();
while (file.hasNext()) {
String data = file.nextLine();
String[] values = data.split(",");
if (values.length >= 1) {
ids.add(values[0]);
for (String index : values) {
System.out.printf("%s \t", index);
}
}
System.out.println();
}
String[] idsArray = new Integer[ids.size()];
ids = ids.toArray(idsArray);
// use idsArray
you can try this:)
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
while(file.hasNext()){
String data = file.nextLine();
String[] values = data.split(",");
for(int key=0;key<values.size();key++){
if (!map.containsKey(key)){
map.put(key, new ArrayList<String>());
}
map.get(key).add(values[key]);
}
}
Integer[] items = new Integer[map.get(0).size()];
for (i = 0; i < map.get(0).size() ; i++) {
items[i]=Integer.valueOf(map.get(0).get(i));
}
I already splitted the String value2 on the char "-" and saved its values in a new array as you can see. Now I wanna seperate the String again on the "," and save it again in a new array but it doesn't work. It always just seperates the second name with the number. And overrites the first. So I got in the first Array on [0]: Peter,2 and in [1]: Leo,1
and in the second array just on [0] Leo and on [1] 1.
I know my for loop is wrong and I don't know how to fix it.
final int value = 2;
final String value2 = "Peter,2-Leo,1";
String[] splittedStringOne = new String[value];
String[] splittedStringTwo = new String[splittedStringOne.length*2];
splittedStringOne = value2.split("-");
for(int i=0;i<splittedStringOne.length;i++) {
splittedStringTwo=splittedStringOne[i].split(",");
Assuming that your splittedStringOne contains the right values at index [0] and [1], in your for loop, you will just overwrite the content of splittedStringTwo.
Since String.split(',') returns an array, you should also make splittedStringTwo two dimensional :
String[][] splittedStringTwo = new String[splitedStringOne.length][2];
This should work for the for loop:
for(int i=0;i<splittedStringOne.length;i++) {
splittedStringTwo[i] = splittedStringOne[i].split(",");
}
note that I added [i] to splittedStringTwo
splittedStringTwo has to be 2 dimensional.
String[][] splittedStringTwo = new String[splitedStringOne.length][2];
for(int i =0; i < splittedStringTwo.length; i++)
splittedStringTwo[i] = splittedStringOne[i].split(",");
Or if you dont want a 2 dimensional array:
String[] splittedStringTwo = new String[splittedStringOne.length*2];
for(int i = 0; i < splittedStringTwo.length; i+=2){
String[] split = splittedStringOne[i].split(",");
splittedStringTwo[i] = split[0];
splittedStringTwo[i+1] = split[1];
}
EDIT:
For question in the comments. Try this out, it is not tested but it should work
String[][] splittedStringTwo = new String[splittedStringOne.length*2][2];
for(int i = 0; i < splittedStringTwo.length; i+=2){
String[] split1 = splittedStringOne[i].split(",");
String[] split2 = splittedStringOne[i+1].split(",");
splittedStringTwo[i][0] = split1[0]
splittedStringTwo[i][1] = split2[0];
splittedStringTwo[i+1][0] = split1[1]
splittedStringTwo[i+1][1] = split2[1];
}
You can use arraycopy to copy the result of splittedStringOne[i].split(","); to the correct position of splittedStringTwo
like:
public class ArrayCopyTest {
#Test public void test() {
final String value2 = "Peter,2-Leo,1";
String[] splittedStringOne = value2.split("-");
String[] splittedStringTwo = new String[splittedStringOne.length*2];
for(int i=0;i<splittedStringOne.length;i++) {
// splittedStringTwo = splittedStringOne[i].split(",");
System.arraycopy(splittedStringOne[i].split(","), 0, splittedStringTwo, i * 2, 2);
}
Assert.assertArrayEquals(splittedStringTwo, new String[]{"Peter", "2", "Leo", "1"});
}
}
I've been trying to split an string by a character and store each split value inside an array.
In C# it can be done by calling the .ToArray() method after the Split() but such method apparently doesn't exits in Java. So I've been trying to do this like this (rs is a string list with elements separated by #) :
String t[] = new String[10];
for (int i = 0; i < rs.size(); i++) {
t = null;
t = rs.get(i).split("#");
}
But the whole split line is passed to an index of the array like:
String x = "Hello#World" -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)
My question is that how can store each spit element in an index of the array like :
t[0] = "Hello"
t[1] = "World"
It sounds like your trying to loop through a list, split them then add the arrays together? What your defining as the problem with the .split method is exactly what the split method does.
ArrayList<String> rs = new ArrayList<>();
rs.add("Hello#World");
rs.add("Foo#Bar#Beckom");
String [] t = new String[0];
for(int i=0;i<rs.size();i++) {
String [] newT = rs.get(i).split("#");
String [] result = new String[newT.length+t.length];
System.arraycopy(t, 0, result, 0, t.length);
System.arraycopy(newT, 0, result, t.length, newT.length);
t = result;
}
for(int i=0;i<t.length;i++) {
System.out.println(t[i]);
}
Works just find output is:
Hello
World
Foo
Bar
Beckom
public class Test {
public static void main(String[] args) {
String hw = "Hello#World";
String[] splitHW = hw.split("#");
for(String s: splitHW){
System.out.println(s);
}
}
}
This produced following output for me:
Hello
World
Try this way:
String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World
It is always good to test beforehand if the string contains a #(in this case), just use String#contains().
if (string.contains("#")) {
// Split it.
} else {
throw new IllegalArgumentException(message);
}
why are you using a loop when the problem is already solved in java..
try this
String x = "Hello#World";
String[] array = x.split("#", -1);
System.out.println(array[0]+" "+array[1]);
I have an ArrayList:
private static ArrayList<String> lista;
static void fileReading() {
inp = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(inFileNev), "ISO8859-1")));
String sor;
while ((sor = inp.readLine()) != null) {
lista.add(sor);
lista.add(System.getProperty("line.separator"));
}
I need the strings from this, not the whole line (like "pakcage" and "asd;").
I tried these but none of these works:
String[] temp=null;
for(String s : lista) {
temp = s.split("\\W+");
}
System.out.println(temp);
I get: [Ljava.lang.String;#6ef53890
If I write println Within the for I get the same, just more of this.
If I use this:
String str ="" ;
for(int i=0; i<lista.size(); i++){
str+=lista.get(i)+" ";
String[] temp = new String[str.length()];
for(int i=0; i < str.length(); i++) {
temp[i]=str.valueOf(i);
System.out.println(temp[i]);
}
I get only numbers, and can't figure out how to get the strings from str.
I need to know the strings indexes, and replace them later.
In this example
String[] temp=null;
for(String s : lista) {
temp = s.split("\\W+");
}
System.out.println(temp);
Trying to print an object will result in invoking its toString() method. In fact you are not printing any String value, but an array of Strings, which is an object.
In your second snippet str.valueOf(i); is returning a "string representation of the int argument."
What you probably want to do is
Split your elements into some table, like you did here temp = s.split("\\W+");
And then iterate through the array using foreach:
Which would look like
for (String s : yourStringArray) {
System.out.println(s);
}
Hope this helps... after almost a year ;)