I have an array list ArrayList<String> firstname; In this I am storing n number of names which have been parsed from an xml file.
Now from this ArrayList I need to take all the names and store it in a Single separate
String names along with a slash(/) between of each names.
For eg firstname= {a, c,f,g,h,j,k}
Now i want it to be as follows names= a/c/f/g/h/j/k
So far I have created a for loop to get values from the ArrayList by its size
String names;
for(int k=0;k<Appconstant.firstname.size();k++) {
names = Appconstant.firstname.get(k);
}
String names = TextUtils.join("/", Appconstant.firstname);
String names;
for(int k=0;k<Appconstant.firstname.size();k++)
{
if(k<=Appconstant.firstname.size()-1)
names += Appconstant.firstname.get(k)+"/";
else
names += Appconstant.firstname.get(k)
}
Though you should be using a StringBuilder instead.
Off the top of my head, but something like this:
StringBuilder builder = new StringBuilder();
for(String name : firstname)
{
builder.append(name).append('/');
}
// Remove last '/'
builder.deleteCharAt(builder.length()-1);
StringBuilder myStrBuilder = null;
for(String aName:yourNameList)
{
myStrBUilder.append(aName+"/");
}
myStrBuilder.deleteCharAt(myStrBUilder.length()-1)
Related
I have a single string as follows
one two
three
four
I would like to split this into an arrayList so that I can get
String[] g = [one,two,three,four]
I think I need to split by newline and by space but something so simple is defeating me
I have tried:
String [] bilbo=null;
List<String> temp=new ArrayList<String>();
bilbo=g.split("\\n|\\r");
for (String d:bilbo) {
if (d!="") {
if (d.matches("\\s")) {
dd = d.split("\\s");
for (String a : dd) {
temp.add(a.trim());
}
} else {
temp.add(d.trim());
}
}
}
Instead of splitting with "\n|\r", you could simply split with "\\s+", which will cover spaces and new lines:
ArrayList<String> list = Arrays.asList(g.split("\\s+"));
I am decomposing a series of 90,000+ strings into a discrete list of the individual, non-duplicated pairs of words that are included in the strings with the rxcui id values associated with each string. I have developed a method which tries to accomplish this, but it is producing a lot of redundancy. Analysis of the data shows there are about 12,000 unique words in the 90,000+ source strings, after I clean and format the contents of the strings.
How can I change the code below so that it avoids creating the redundant rows in the destination 2D ArrayList (shown below the code)?
public static ArrayList<ArrayList<String>> getAllWords(String[] tempsArray){//int count = tempsArray.length;
int fieldslenlessthan2 = 0;//ArrayList<String> outputarr = new ArrayList<String>();
ArrayList<ArrayList<String>> twoDimArrayList= new ArrayList<ArrayList<String>>();
int idx = 0;
for (String s : tempsArray) {
String[] fields = s.split("\t");//System.out.println(" --- fields.length is: "+fields.length);
if(fields.length>1){
ArrayList<String> row = new ArrayList<String>();
System.out.println("fields[0] is: "+fields[0]);
String cleanedTerms = cleanTerms(fields[1]);
String[] words = cleanedTerms.split(" ");
for(int j=0;j<words.length;j++){
String word=words[j].trim();
word = word.toLowerCase();
if(isValidWord(word)){//outputarr.add(word);
System.out.println("words["+j+"] is: "+word);
row.add(word_id);//WORD_ID NEEDS TO BE CREATED BY SOME METHOD.
row.add(fields[0]);
row.add(word);
twoDimArrayList.add(row);
idx += 1;
}
}
}else{fieldslenlessthan2 += 1;}
}
System.out.println("........... fieldslenlessthan2 is: "+fieldslenlessthan2);
return twoDimArrayList;
}
The output of the above method currently looks like the following, with many rxcui values for some name values, and with many name values for some rxcui:
How do I change the code above so that the output is a list of unique pairs of name/rxcui values, summarizing all relevant data from the current output while removing only the redundancies?
If you just need a Collection of all words, use a HashSet Sets are primarily used for contains logic. If you need to associate a value with your string use a HashMap
public HashSet<String> getUniqueWords(String[] stringArray) {
HashSet<String> uniqueWords = new HashSet<String>();
for (String str : stringArray) {
uniqueWords.add(str);
}
return uniqueWords;
}
This will give you a collection of all the unique Strings in your array. If you need an ID use a HashMap
String[] strList; // your String array
int idCounter = 0;
HashMap<String, Integer> stringIDMap = new HashMap<String, Integer>();
for (String str : strList) {
if (!stringIDMap.contains(str)) {
stringIDMap.put(str, new Integer(idCounter));
idCounter++;
}
}
This will provide you a HashMap with unique String keys and unique Integer values. To get an id for a String you do this:
stringIDMap.get("myString"); // returns the Integer ID associated with the String "myString"
UPDATE
Based on the question update from the OP. I recommend creating an object that holds the String value and the rxcui. You can then place these in a Set or HashMap using a similar implementation to the one provided above.
public MyObject(String str, int rxcui); // The constructor for your new object
MyObject mo1 = new MyObject("hello", 5);
Either
mySet.add(myObject);
will work or
myMap.put(mo1.getStr, mo1.getRxcui);
What is the purpose of the unique word ID? Is the word itself not unique enough since you are not keeping duplicates?
A very basic way would be to keep a counter going as you are checking new words. For each word that doesn't already exist you could increase the counter and use the new value as the unique id.
Lastly, might I suggest you use a HashMap instead. It would allow you to both insert and retrieve words in O(1) time. I am not entirely sure what you are going for, but I think the HashMap might give you more range.
Edit2:
It would be something a little more along these lines. This should help you out.
public static Set<DataPair> getAllWords(String[] tempsArray) {
Set<DataPair> set = new HashSet<>();
for (String row : tempsArray) {
// PARSE YOUR STRING DATA
// the way you were doing it seemed fine but something like this
String[] rowArray = row.split(" ");
String word = row[1];
int id = Integer.parseInt(row[0]);
DataPair pair = new DataPair(word, id);
set.add(pair);
}
return set;
}
class DataPair {
private String word;
private int id;
public DataPair(String word, int id) {
this.word = word;
this.id = id;
}
public boolean equals(Object o) {
if (o instanceof DataPair) {
return ((DataPair) o).word.equals(word) && ((DataPair) o).id == id;
}
return false;
}
}
I have an object Keyword that stores a String with the text of the keyword and a set o keywords (Set<Keyword>) that I need to transform into a String array. Is there a quick/easy way to do this or I need to iterate the set and add each keyword one by one?
EDIT:
For those asking for Keyword class:
#Entity
public class Keyword {
// ...
#Basic
private String value;
// ...
// Getters & Setters
}
Every class that implements Collection intefrace (and that includes Set) has toArray() method:
String[] array= set.toArray(new String[0]);
In case of a set that is parametrized with some other type, e.g. Set<Keyword> you would have to do something like:
Keyword[] array= set.toArray(new Keyword[0]);
String[] stringArray= new String[array.length];
for (int i=0; i<array.length; i++) {
stringArray[i]= array[i].getThatString();
}
Try this:
String[] arr = set.toArray(new String[set.size()]);
... is what I would have said, if you had a Set<Object>.
No, there is no way to directly convert a Set<Keyword> to a String[] since there is no direct relationship between Keyword and String. You will have to iterate over the set:
String[] arr = new String[set.size()];
int i = 0;
for (Keyword word : set)
arr[i++] = word.toString();
If you use Guava, you may use this:
Lists.transform(Lists.newArrayList(theSet), Functions.usingToString())
.toArray(new String[theSet.size()])
And this only scratches the surface of what Guava can actually do.
There is no specific way to do this . You can either convert Set to Object[] using set.toArray and then iterate over the array
or
iterate over the set directly
You may need to add toString() method to your Keyword class as shown below. Or you can use a separate transformer class/method.
class Keyword {
private String value;
Keyword(String v) {
this.value = v;
}
public String toString() {
return value;
}
}
.
I would say iterate the set and add each keyword one by one is your best possible strategy.
System.out.println(toStringArray(set));
.
private static String[] toStringArray(Collection<?> set) {
String[] arr = null;
if (set != null) {
arr = new String[set.size()];
int i = 0;
for (Object o : set) {
arr[i++] = o.toString();
}
}
return arr;
}
.
However if you really want, you can have a dirty workaround as shown below. Only issue here is that your keyword value cannot contain comma (,) as it is used by split() method.
String str = set.toString();
str = str.substring(1, str.length() - 1);
String[] asStringArray = str.split(",");
System.out.println(asStringArray);
I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));
I am attempting to parse the value of the elements in a List declared as thus:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
The values are such as this:
a:1-2
b:3-5
but I want one ArrayList with the first number (i.e. 1, 3) and another with the second (i.e. 2, 5). I have this worked out... Sorta:
String delims= "\t"; String delim2= ":"; String delim3= "-";
String splits2[]; String splits3[]; String splits4[];
Map<String,String> dupMap = new TreeMap<String, String>();
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<String> parsed2 = new ArrayList<String>();
ArrayList<String> parsed3 = new ArrayList<String>();
ArrayList<String> parsed3two= new ArrayList<String>();
double uniques = uniqueList.size();
for(int a=0;a<uniques;a++){
//this doesn't work like it would for an ArrayList
splits2 = uniqueList.split(delim2) ;
parsed2.add(splits2[1]);
for(int q=0; q<splits2.length; q++){
String change2 = splits2[q];
if(change2.length()>2){
splits3 = change2.split(delim3);
parsed3.add(splits3[0]);
String change3=splits3[q];
if (change3.length()>2){
splits4 = change3.split(delims);
parsed3two.add(splits4[0]);
}
}
}
}
uniqueList.split does not work however and I don't know if there is a similar function for List. Is there any suggestions?
If you know that all of your data is in the form [something]:[num]-[num], you can use a regular expression like this:
Pattern p = Pattern.compile("^([^:]*):([^-]*)-([^-]*)$");
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
Matcher m = p.matcher(src);
if( m.find() && m.groupCount() >= 3) {
String firstValue = m.group(1); // value to left of :
String secondValue = m.group(2); // value between : and -
String thirdValue = m.group(3); // value after -
// assign to arraylists here
}
}
I didn't actually put the code in to add to the specific ArrayLists because I couldn't quite tell from your code which ArrayList was supposed to hold which value.
Edit
Per Code-Guru's comment, an implementation using String.split() would go something like this:
String pattern = "[:\\-]";
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
String[] parts = src.split(pattern);
if (parts.length == 3) {
String firstValue = parts[1]; // value to left of :
String secondValue = parts[2]; // value between : and -
String thirdValue = parts[3]; // value after -
// assign to arraylists here
}
}
Both approaches are pretty much the same in terms of efficiency.
From what I understand of your question, I would proceed as follows:
for each String in uniqueList
parse the string into a character and two integers (probably using a single call to [String.split()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String, int))
insert the first integer into an List
insert the second integer into another List
This is in pseudocode. Translating into Java is left as an exercise to the reader.