I have an arraylist like below
List<String> list = new ArrayList<String>();
list.add("P Pro Rata(Average Cost w/Tax Lots)");
list.add("A apple is good");
list.add("B ball is nice");
list.add("C cat is not there");
I want the first space of each element in the array list should be replaced with : operator(only first space and for each element)
so output should be
A:apple is good
B:ball is nice
C:cat is not there
I have a solution which iterates and creates new element and add it to new list and using that new list
can any one come up with best solution ?
Try this:
for(int i=0;i<list.size();i++) {
list.set(i,list.get(i).replaceFirst(" ", ":"));
}
You can use indexOf to find the first occurance of a space in the strings as such:
for (String s : list) {
int index = s.indexOf(" ");
String prefix = s.substring(0, index);
String suffix = s.substring(index+1);
System.out.println(prefix + ":" + suffix);
}
Use for each to iterate array list and replaceFirst will help you replace first char
int i=0;
for (String s : list){
list.set(i,s.replaceFirst(" ", ":"));
i++;
}
Related
I have a string array of full names with different surnames, i.e.
String[] tempArray = {"rakesh bhagat", "mayur suryavanshi", "prathamesh ambre", "akash tare", "abhi ingle", "rutvik patil"};
I want to create a new string of all names except one name, i.e.
temp = "rakesh bhagat, mayur suryavanshi, prathamesh ambre, akash tare, abhi ingle, rutvik patil";
So here I want to remove "mayur suryavanshi" from array without using index because I don't know index of that item, but I have certain condition like
if(tempArray[i].endsWith("suryawanshi")){}
Which I can use in for loop.
I tried to make new string with removing those item in for loop
String result = joiner.toString();
String temp = null;
for (int i = 0; i < tempArray.length; i++) {
if (tempArray[i].endsWith("suryavanshi")) {
continue;
}
if (temp == null) {
temp = tempArray[i];
} else {
temp = temp + ", " + tempArray[i];
}
}
Avoid concatenating string in the loop, each concatenation str1 + str2 in a new string stored as a separate object. As the consequence of this, lots of intermediate strings which you don't need would be created.
Use StringBuilder or other built-in mechanisms when you need to join together more than just a couple of strings.
Collectors.joining()
It can be done with Stream API using built-in Collector joning():
String[] tempArray = {"rakesh bhagat", "mayur suryavanshi", "prathamesh ambre", "akash tare", "abhi ingle", "rutvik patil"};
String result = Arrays.stream(tempArray)
.filter(str -> !str.endsWith("suryavanshi")) // retain only elements which don't end with "suryavanshi"
.collect(Collectors.joining(", "));
StringJoiner
Alternatively, you can use a so-called enhanced for-loop (also known as for-each) and StringJoiner :
StringJoiner joiner = new StringJoiner(", ");
for (String str : tempArray) {
if (str.endsWith("suryavanshi")) continue;
joiner.add(str);
}
String result = joiner.toString();
I need to print all arraylist values at a time using concat.
Here is my code:
ArrayList<String> lst = new ArrayList<String>();
lst.add("hi");
lst.add("hello");
Iterator<String> itr = lst.iterator();
String result = null;
while(itr.hasNext()) {
Object element = itr.next();
result = element + " ";
}
System.out.println(result);
The expected result should be hi hello.
The current output however is hello (there is also a whitespace at the end).
Please prefer the List interface to the ArrayList concrete type. Assuming you are using Java 8+, you might use a Stream and Collectors.joining (and Arrays.asList) like
List<String> lst = Arrays.asList("hi", "hello");
String r = lst.stream().collect(Collectors.joining(" "));
System.out.println(r);
Which outputs
hi hello
As requested.
The error in your code is pretty small. In each iteration you assign a value to the result variable. However instead of updating your existing content you just erase it and enter a new value.
You do result = element + " ". But it should be something like result = result + element + " " or the same in short:
result += element + " ";
This way the first iteration will save hi in it and after that hello gets appended resulting in hi hello (instead of overriding the content of the first iteration).
Note that it now also has the whitespace at the end. You could delete it with result = result.substring(0, result.length() - 1). Or not add it in the last iteration, but then you need to count the iterations.
Please note that Java has a class StringJoiner that does exactly what you want, joining some elements together and also using a delimiter like whitespace. You use it like this:
StringJoiner sj = new StringJoiner(" ");
while(itr.hasNext()) {
Object element = itr.next();
sj.add(element);
}
String result = sj.toString();
Also note that since Java 8 there is an even shorter version of it:
String result = String.join(" ", list);
let's say i have this array list
List<String> Speach2R = new ArrayList<>();
Speach2R.add(0, "Hello");
Speach2R.add(1, "yes");
Speach2R.add(2, "Hi");
and i wanna say
if (messages.contains(any of Speach2R strings){
said = true;
}
also i want to find the int of the founded message, like if message "Hi" exists
int MessageNumber = 2
If you message is like a sentence, you need to iterate over the word of the List
Set<Integer> indexes = new TreeSet<>();
String message = "Hi, my name is john, and Hello";
for (String word : Speach2R){
if (message.contains(word)){
indexes.add(Speach2R.indexOf(word));
}
}
It will iterate over the word of the List, and store in a Set all the indexes of the word it founds
System.out.println("Your message contains :");
for (Integer i : indexes){
System.out.println(Speach2R.get(i) + ", at index " + i);
}
And with that you will print all the words found + their index in the List
You can use the ArrayList#contains method since your List consists of Strings and ArrayList#indexOf for the index.
It would look like this
String message = "yes";
boolean found = false;
int index = -1;
if(speach2R.contains(message)){
found = true;
index = speach2R.indexOf(message);
}
With the java 8 Stream API, you can do something like this :
messages.stream().filter( Speach2R::contains ).findAny().isPresent()
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.
Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...
I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?
So question is that the right way and what / how to realise that.
Here is my code so far:
public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";
//declaration
String[] stringArray;
String delimiter = ";";
// allocates memory for 59 strings
stringArray = new String[59];
// split the String after separator ";"
stringArray = strLine.split(";", -1);
// print array
for(int j = 0; j < stringArray.length; j++) {
System.out.println(j + " " + stringArray[j]);
}
}
I recommend you to split the string with delimiter ; and add separated Strings to a List, where you can easily validate with the Collections.frequency() static method returning the number as int of the occurence.
String[] values = strLine.split(";");
List<String> list = Arrays.asList(values);
if (Collections.frequency(list, list.get(0) > 1) {
System.out.println("The first value is not unique in the list");
}
Since Java 8 feel free to use Stream:
if (list.stream().filter(a -> a.equals(list.get(0))).count() > 1) {
System.out.println("The first value is not unique in the list");
}
// allocates memory for 59 strings
stringArray = new String[59];
// split the String after separator ";"
stringArray = strLine.split(";", -1);
Initializing the String[59] isn't helping you; the split method is just returning something that overwrites it immediately afterwards.
If you needed to check for any duplicates, using a HashSet would help here.
If you only need to make sure the first element isn't duplicated, you can just do it in a loop. You've already got one, so...
// print array
for(int j = 0; j < stringArray.length; j++) {
if (stringArray[0].equals(stringArray(j)) {
System.out.println("Duplicate!");
}
System.out.println(j + " " + stringArray[j]);
}
}
To check if the first element is unique, you can use the following:
Collections.frequency(Arrays.asList(stringArray), stringArray[0]) == 1
This returns a boolean that is true if the first element of stringArray is unique, otherwise false.
For each line, put its Referenz in a HashSet. Then checking if a subsequent Referenz is unique would be as simple as referenzSet.contains(theNewReferenz)
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?