I need to assign an ArrayList's data into a String variable.
Using following code I am getting tempSeats equals jack, ravi, mike,
ArrayList<String> userSelectedSeats = new ArrayList<String>();
userSelectedSeats.add("jack");
userSelectedSeats.add("ravi");
userSelectedSeats.add("mike");
for (String s : userSelectedSeats) {
tempSeats += s + ", ";
}
but output should be jack, ravi, mike What modification should I do to my code?
Let Java's streams do the heavy lifting for you:
String tempSeats = userSelectedSeats.stream().collect(Collectors.joining(", "));
You're adding a comma after the end of every item, even the last item. You only want to add a comma if the item isn't the last item in the list. This is called joining.
If you're using Java 8, you can do
userSelectedSeats.stream().collect(Collectors.joining(", "))
Otherwise see this question for further info.
A simple String.join will accomplish the task at hand.
String result = String.join(", ", userSelectedSeats);
Replace the for loop with this,
tempSeats = TextUtils.join(", ",userSelectedSeats);
Hope it helps!
String c;
ArrayList<String> userSelectedSeats = new ArrayList<String>();
userSelectedSeats.add("jack");
userSelectedSeats.add("ravi");
userSelectedSeats.add("mike");
for (int i=0; i < userSelectSeats.length(); i++)
c += userSelectSeats.get(i).toString()+ ",";
Related
i have String Array like this:
String[] q1={"AAA-BBB","AAA-CCC","AAA-DDD"}
and i want result like this
temp={"BBB","CCC","DDD"}
i tried below code but the result is wrong
for(int i=0;i<q1.length;i++){
ArrayList<String> temp=new ArrayList<>(Arrays.asList(q1[i].split("AAA-")));
}
Try like this:
ArrayList<String> temp=new ArrayList<>();
for(int i=0;i<q1.length;i++){
String[] array = q1[i].split("-");
temp.add(array[1]);
}
You could use substring:
ArrayList<String> temp = new ArrayList<>();
for(int i=0; i<q1.length; i++){
temp.add(q[i].substring(q[i].indexOf('-') + 1, q[i].length()))
}
you find error Because you use split
Splits this string around matches of the given regular expression.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
q1[i].split("AAA-")
in this line you got 2 result splited 0 = "" AND 1 = "BBB"
so you need to pick the sec result
you have multi Solution
like https://stackoverflow.com/a/50234408/6998825 said
String[] array = q1[i].split("-");
temp.add(array[1]);
//change this q1[i].split("AAA-") to
q1[0].substring(4)
if your AAA- is not going to change
Have you tried creating the ArrayList outside of the loop? As previously you were creating a new ArrayList for every element in your string array
ArrayList<String> temp = new ArrayList<>();
for(int i=0;i<q1.length;i++){
temp.add(q1[i].substring(4);
}
Assuming that "AAA-" is not going to change.
Suppose I have LinkedhashMap<String, List> myLHM = new LinkedHashMap<>()
Values of myLHM :
<Roy,[1,2,3]>
<Roy,[14,15,16]>
<Neha,[1,5,6]>
<Neha,[11,12,13]>
<Jane,[11,8,9]>
In above eg., Roy and Neha is repetitive/duplicate.
Is it possible to hold duplicate keys in myLHM ? Because I'm not able to store duplicate keys
No? Then what is the alternative to LinkedHashMap to hold duplicate keys?
TIA!
Edit: Those two Roy and Neha are each the same person
I don't know of any map in the standard java library that can hold duplicate keys, but Guava is an excellent extension to the normal java Collections (and more) done by Google. There you have Multimap which can hold several values for the same key (I guess this is what you want in the end). The main benefit I find in using such a library/implementation is that it will take care of everything for you associated with the storage of the values and you don't need to bother about implementing it yourself.
PS: Guava is not just about Collections, which I think it's another Pro why you should check it out.
Add a List of items by key. Whenever you insert, if key was found, just add to the collection. When not found, add a new colelction with current item.
I solved this by myself.
What I did is used :
LinkedHashMap<String, ArrayList<ArrayList>> myLHM = new LinkedHashMap<>() ;
Inserted into it as:
ArrayList<ArrayList> multiDimArray = new ArrayList<>();
ArrayList list = new ArrayList();
list.add("abc");//some string 1
list.add("lmn");//some string 2
list.add("xyz");//some string 3
multiDimArray.add(list);
myLHM.put("abc"/*use your variable OR pass value like myList.get(position)*/,multiDimArray);
Fetched / Retrieved values as:
List tempNames=new ArrayList();
Iterator myVeryOwnIterator = myLHM.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
tempNames.add(myVeryOwnIterator.next());
}
ArrayList<ArrayList> tempArrayList = new ArrayList();
for (int i=0;i<tempNames.size();i++){
tempArrayList.addAll(myLHM.get(tempNames.get(i)));
}
String item = null; int year = 0; int amount = 0;
for (int i=0;i<tempArrayList.size();i++) {
for (int j=0;j<tempArrayList.get(i).size();j++){
if(j==0){
item = (String) tempArrayList.get(i).get(j);
item = item.replaceAll("\\s", "_");
} else if (j==1){
year = Integer.valueOf(tempArrayList.get(i).get(j).toString());
} else if (j==2){
amount = Integer.valueOf(tempArrayList.get(i).get(j).toString());
} else {
Log.e("Problem","for loop error");
}
}
db.execSQL("INSERT INTO ch // my insert query...
VALUES(" +"'" + item +"'," + year +"," + amount +"," + id +");");
}
I had a doubt while using soap ,how to split a string,Is there any possibility.
//this the original data
Afternoon-99127.79;
Night-67236.27;
Morning-61876.65;
Evening-20271.42;
Housekeeping-5444.05;
I need;
Afternoon 99127.79
Night 67236
Morning 61876.65;
Evening 20271.42;
Housekeeping 5444.05;
I split using semicolon and then i don't know how to use the sub strings,Use of start and end index i don't know how to give the values..Actually i want to split before "-" and after "-".
Try this way,hope this will help you to solve your problem.
String soapString = "Afternoon-99127.79;" +"Night-67236.27;" +"Morning-61876.65;" +"Evening-20271.42;" +"Housekeeping-5444.05;";
String[] splitedArray = soapString.split(";");
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
for (int i=0;i<splitedArray.length;i++){
HashMap<String,String> row =new HashMap<String, String>();
row.put("firstString",splitedArray[i].split("-")[0]);
row.put("secondString",splitedArray[i].split("-")[1]);
list.add(row);
}
for (HashMap<String,String> data : list){
System.out.println(data.get("firstString") +" "+data.get("secondString"));
}
String total_string = "Afternoon-99127.79;Night-67236.27;Morning-61876.65;Evening-20271.42;Housekeeping-5444.05;";
String[] spilted_string = total_string.split(";");
for (int i=0;i<spilted_string.length;i++){
System.out.println(spilted_string[i].split("-")[0]);
System.out.println(spilted_string[i].split("-")[1]);
}
DEMO
Split by ; which'll give you an array of elements separated by -. Then split each array item by -
public class SplitEx {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String data = "Afternoon-99127.79;Night-67236.27;Morning-61876.65;Evening-20271.42;Housekeeping-5444.05;";
String[] a = data.split(";");
String[] b = new String[a.length];
for (int i = 0 ; i < a.length; i++)
{
System.out.println(a[i]);
b[i] = a[i].replace("-"," ");
}
for (int i = 0 ; i < b.length; i++)
{
System.out.println(" " +b[i]);
}
}
}
OUTPUT OF ARRAY B
Afternoon 99127.79
Night 67236.27
Morning 61876.65
Evening 20271.42
Housekeeping 5444.05
use Strin[] a = myString..split("-");
This code piece will split the String by "-" and store it in string array.
But I recommend you to use Sparse array. Transfer your data using SparseArray and accept it in the same way. It is faster than Hashmap. Try it.
ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.
I am working on android applications. I created two pages i.e Page1 and Page2. Page2 contains an arraylist with repeated values. I am passing a value from page1 and
I want to find the number of occurences of the value(coming from page1) in the arraylist in page2. Please suggest what should I have been done to do that task.
Thanks in advance
below is the solution for your problem
ArrayList<String> list = new ArrayList<String>();
Collections.frequency(list, "Key/value to search");
reference link >> how to count occurance in arraylist/list
Collection.frequency() is what you needed,
Try something like,
ArrayList<Integer> intList // your list
Set<Integer> Values = new HashSet<Integer>;
Values.addAll(intList); // all duplicates removed.
for (Integer i : Values) {
int occurrences = Collections.frequency(intList, i);
Log.e(i ," occurs " + occurences + " times.");
}
Use Collections.frequency() method...
Eg:
public class ArrFrq {
public static void main(String[] args){
ArrayList<String> s = new ArrayList<String>();
s.add("Vivek");
s.add("Vicky");
s.add("Vivek");
System.out.println(Collections.frequency(s, "Vivek"));
}
}