Printing out array elements based on elements contents (Java) - java

I have an array of String like so:
array[0] = "1 4"
array[1] = "2 0"
array[2] = "2 1"
array[3] = "4 2"
and would like to process the array and print out the second part of the array element
on the same line when the first part of the array element have duplicates, like this:
4
0 1
2
I've been trying ages to work this out but I keep getting more confused...
Processing is based on consecutive lines.

It looks like a straight-forward Java coding problem to me:
String lastKey = null;
for (String str : array) {
String[] parts = str.split(" ");
if (parts[0].equals(lastKey)) {
System.out.print(" ");
} else if (lastKey != null) {
System.out.println();
}
System.out.print(parts[1]);
lastKey = parts[0];
}
System.out.println();
This assumes that your input file is ordered on the first field ...

Looking at the comments, it looks like you could use MultiMaps and simplify the design
MultiMap mhm = new MultiHashMap();
for ( string line: array) {
String []pair = line.split(" ");
mhm.put(pair[0],pair[1]);
}
for (Collection coll = (Collection) mhm.values() ) {
//print all values from collection?
}

I would check index n and n+1 of the array list. Tokenize both the strings and compare the first elements. If the first elements are the same, you can print the second element from both the strings in one line.
I assume that you are not looking for 2 specifically as the first number and you want to check only consecutive elements of the list. Is that the case?

Related

Concatenating String Arrays in For Loops with String conditions

I currently am running a for loop which reads a List object and then splits them into arrays. Here is the sample code:
List<String> lines = Arrays.asList("foo,foo,foo","bar,baz,foo","foo,baz,foo", "baz,baz,baz", "zab,baz,zab");
for (String line : lines){
String[] array = line.split(",");
String[] arraySplit2 = array[0].split(",");
System.out.print(Arrays.toString(arraySplit2));
}
The output is:
[foo][bar][foo][baz][zab]
I wish to concatenate the array strings into a single one under the loop so that it displays:
[foo, bar, foo, baz, zab]
I'm having a bit of trouble because the conditions of the loop prevent me from doing the increase int i trick and using System.arraycopy(). I'm open to ideas such as changing the structure of the loop itself.
You seem to be trying to create an array out of first items from each line.
First, So you need to create the result array first with the size of number of lines:
String[] result = new String[lines.size()];
int index = 0;
You do not need the second split, in the for loop populate the result array:
result[index++] = array[0]
After the loop print your result array.
Not 100% sure on what you want, but I guess something like this:
List<String> outList = new ArrayList<String>();
for (String line : lines) {
String[] array = line.split(",");
outList.add(array[0]);
}
String[] outStr = outList.toArray(new String[0]);
System.out.println(Arrays.toString(outStr));

How to Split an ArrayList in Android Using JAVA?

Here is the code to put values in ArrayList and I am unable to split the arraylist with ",". Can someone please help me as to how to achieve this task ?
spinnerArrayList = new ArrayList<String>();
spinnerArrayList.add(menuFieldInstance.getFieldValues());
Log.i("spinnerArrayList",""+spinnerArrayList);
//for(int j=0;j<spinnerArrayList.size();j++)
//{
Log.i("spinnerArrayList after splitting ,",""+spinnerArrayList.get(0).split(","));
//}
Here is the Logcat of Spinner ArrayList and SpinnerArrayList after splitting.............
02-10 22:00:48.285: I/spinnerArrayList(19378): [0100~Avon & Somerset,0200~Bedfordshire,0300~Cambridgeshire,0400~Cheshire,0500~City of London,0600~Cleveland,0700~Cumbria,0800~Derbyshire,0900~Devon & Cornwall,1000~Dorset,1100~Durham,1200~Essex,1300~Gloucestershire,1400~Greater Manchester,1500~Hampshire,1600~Hertfordshire,1700~Humberside,1800~Kent,1900~Lancashire,2000~Leicestershire,2100~Linconshire,2200~Merseyside,2300~Metropolitan,2400~Norfolk,2500~Northamptonshire,2600~Northumbria,2700~North Yorkshire,2800~Nottinghamshire,2900~South Yorkshire,3000~Staffordshire,3100~Suffolk,3200~Surrey,3300~Sussex,3400~Thames Valley,3500~Warwickshire,3600~West Mercia,3700~West Midlands,3800~West Yorkshire,3900~Wiltshire,4000~Dyfed,4100~Gwent,4200~North Wales,4300~South Wales,4400~Royal Ulster,4500~Strathclyde,4600~Central Scotland,4700~Dumfries and Galloway,4800~Fife,4900~Grampian,5000~Lothian and Borders,5100~Northern Scotland,5200~Tayside,5300~Gurnsey,5400~States of Jersey,5500~Isle of Man,NO~No Police Response,THAM~THAMES VALLEY,WEST~WEST MIDLANDS POLICE,5600~Buckinghamshire]
02-10 22:00:48.285: I/spinnerArrayList after splitting ,(19378): [Ljava.lang.String;#41b9a498
// try to print this way then you getting actual value at index becz your try to print String[] object rather each index value so do this way
spinnerArrayList = new ArrayList<String>();
spinnerArrayList.add("");
for (int i=0;i<spinnerArrayList.size();i++){
String[] splitedValue = spinnerArrayList.get(i).split(",");
for (int j=0;j<splitedValue.length;j++){
Log.i(i+" at ArrayIndex "+j+" at splitedIndex Value is >> ",splitedValue[j]);
String[] splitedValue1 = splitedValue[j].split("~");
if(splitedValue1.length==1){
continue;
}
for (int k=0;k<splitedValue1.length;k++){
Log.i(j+" at splitedIndex "+k+" at splited1Index Value is >> ",splitedValue1[k]);
}
}
}
You can't split ArrayList. You can split String, e.g "I am some String, you can split me".split(",") will return an array of 2 Strings, but ArrayList is a data structure which holds some Strings and it doesn't mean that they are separated with comma. You can try to split each item of the list, e.g.
for (String s : spinnerArrayList) {
String[] res = s.split(",");
// do smth with res
}
spinnerArrayList.get(0).split(",") doesn't split "the arrayList" it splits the string at index zero, and since the returned result is an array of strings - you can't concatenate it using the + operator to another string:
Log.i("spinnerArrayList after splitting ,",""+spinnerArrayList.get(0).split(","));
Read the splitted string into a String array first:
String[] arr = spinnerArrayList.get(0).split(",");
and then loop the array and print the values"
for(String val: arr){
Log.i(val);
}

2D Array but with indexing - java

I'm looping into a number of rows and trying to filter these rows with some if statements. within each if statement I need to have an index for a number of elements. I could have done that using 2d String[][] but the problem is I don't know what is the size of each row at this stage.
I'm looking to store my data like the following :
0 1 3 4 5 6 7 etc..
0 str str str str str str str
1 str str str
2
3 str str str str str str
Any suggestion would be appreciate it
Edit:
Sorry if my question wasn't clear. But I'll explain it more here.
My Loop looks like this:
newArrayList
for (i; i < List ;i++)
{
if(...)
{
newArrayList.add.(0, List.get(i));
} else if(...)
{
newArrayList.add.(2, List.get(i));
} else if(...)
{
newArrayList.add.(6, List.get(i));
}
}
The above code doesn't work but I'm just trying to explain what I need to do actually! My if statements can occur several times and I would like to consider an index for each if statement expectation plus a set of strings. Thanks.
You could try an ArrayList of ArrayList's:
ArrayList<ArrayList<String>> strings = new ArrayList<ArrayList<String>>();
strings.add(new ArrayList<String>()); // Adding a first array to the 'array of arrays'
strings.get(0).add("String1"); // Add a string to the first array,
// Similar to: arr[0][0] = "String1"
//To access them element by element use a double for, note that "s" is each element
for (ArrayList<String> l : strings) {
for (String s : l) {
}
}
PS: An ArrayList<Object> is like an array Object[] but more flexible. It has some useful methods like:
arr_list.get(index); // Getting an object in position 'index'
arr_list.add(object); // Adding an element (Similar to assignment in arrays)
Edit
If you know the number of "rows" then you have to add them to the array of arrays. With this for you are "creating the empty rows of your array":
Rows:
0
1
...
n
for (int i = 0; i < n; i++) { // n is the number of "rows"
strings.add(new ArrayList<String>());
}
Then add an element to a "row":
strings.get(0).add("String1"); // get(0) to obtain the first row, get(1) to obtain the second...
If your index is consecutive form 0 to n and you are inserting them in that order, but n is not known in advance: There are two classical solution:
1) If you do it with a pre-allocated fixed array, you obviously need two passes. The first pass is scanning the row and counting the elements. The second pass is then creating the index.
2) You can do it with a collection allowing dynamic growth via an .add(item) method, like List
If you will convert the collection to an fixed size array later, then it is maybe faster to use method 1) since the add method may be slower due to memory management / allocation / re-allocation.
If your index is consecutive form 0 to n and n is known in advance, but you are inserting the elements not in that order:
You should use solution 1) above.
If your index is not consecutive and n is known known in advance:
3) You create a Map<Integer,String> strings and add the elements via strings.put(index, string) (in any order).
If your index is not unique (as we have finally found out):
4) You crate a Map<Integer,ArrayList<String>> stringMap and add elements via
addStringForIndex(String string, Integer index)
{
listForString = stringMap.get(index);
if(listForString == null) {
listForString = new ArrayList<String>;
map.put(index, listForString);
}
listForString.add(string);
}
If you don't know the size of your array, you could use a List implementation, for example:
ArrayList<ArrayList<String>> 2D = new ArrayList<ArrayList<String>>();
And then use a for-each loop

how to split this string[LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,] as my requirement in java

hello every one i got a string from csv file like this
LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,
how to split this string with comma i want the array like this
s[0]=LECT-3A,s[1]=instr01,s[2]=Instructor 01,s[3]=teacher,s[4]=instr1#learnet.com,s[5]=,s[6]=,s[7]=,s[8]=male,s[9]=phone,s[10]=,s[11]=
can anyone please help me how to split the above string as my array
thank u inadvance
- Use the split() function with , as delimeter to do this.
Eg:
String s = "Hello,this,is,vivek";
String[] arr = s.split(",");
you can use the limit parameter to do this:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example:
String[]
ls_test = "LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,".split(",",12);
int cont = 0;
for (String ls_pieces : ls_test)
System.out.println("s["+(cont++)+"]"+ls_pieces);
output:
s[0]LECT-3A
s[1]instr01
s[2]Instructor 01
s[3]teacher
s[4]instr1#learnet.com
s[5]
s[6]
s[7]
s[8]male
s[9]phone
s[10]
s[11]
You could try something like so:
String str = "LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,";
List<String> words = new ArrayList<String>();
int current = 0;
int previous = 0;
while((current = str.indexOf(",", previous)) != -1)
{
words.add(str.substring(previous, current));
previous = current + 1;
}
String[] w = words.toArray(new String[words.size()]);
for(String section : w)
{
System.out.println(section);
}
This yields:
LECT-3A
instr01
Instructor 01
teacher
instr1#learnet.com
male
phone

Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);

Categories