convert List<String> to a static string if possible - java

I am trying to wrap my head around List<String> I have a dynamicly created array List<String> selected_tags That I would like to convert to break apart the elements and place a "%" inbetween each element so I can use the new string in a http call.
Creat my new List :
public List<String> selected_tags = new ArrayList<String>();
Fill my List string
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
I then need to use selected_tags in my url
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags="+ BROKEN DOWN LIST<STRING>);
I would like for it to look like
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags=tag1%tag2%tag3);

StringBuilder s = new StringBuilder();
boolean first = true;
for (String tag : selected_tags) {
if (!first)
s.append("%");
else
first = false;
s.append(tag);
}
String myUrlString = "tags=" + s.toString();

actually, you should have something like
StringBuilder sb = new StringBuilder();
if(selected_tags.size() > 0) {
sb.append(selected_tags.get(0);
for(int i = 1 ; i < selected_tags.size(); i++) {
sb.append("%");
sb.append(selected_tags.get(i));
}
}
return sb.toString();

StringBuilder result = new StringBuilder();
String prepend = "tags=";
for( String tag : selected_tags ){
result.append(prepend).append(tag);
prepend = "%";
}
String resultString = result.toString();

StringBuilder sb = new StringBuilder();
for (String tag : selected_tags) {
sb.append("%").append(tag);
}
sb.replace(0,1,"tags=");

Related

How to apply for loop on first n vlalues of arraylist

I have an arraylist in which I have ESSID, BSSID, Strenght of access Point on first three indexes, and from Index 4 to 6 I have again ESSID, BSSID, Strength of another AccessPoint. I want to store this list in database like first three values save in one row of table. and next three values save in 2nd row of table.
String[] namesArr = new String[arrayList2.size()]; //conver arraylist to array
for (int j = 0; j < arrayList2.size(); j++){
namesArr[j] = arrayList2.get(j);
int length = namesArr[j].length();
for (int k = 0; k < length; k += 3) {
ssid = namesArr[k];
bssid = namesArr[k + 1];
rssid = namesArr[k + 2];
}
insertValues(this);
}
public void insertValues(View.OnClickListener view){
SendData send = new SendData(this);
send.execute(bssid,ssid,rssid);}
I have made a class to store this data in database that works fine.
public class SendData extends AsyncTask<String, Void, String> {
AlertDialog dialog;
Context context;
public SendData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String data = "";
String result = "";
String MAC = voids[0];
String Name = voids[1];
String Strength = voids[2];
String con_Str = "http://10.5.48.129/Webapi/accesspoints_data/create.php";
try{
URL url = new URL(con_Str);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream out_Stream = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_Stream, "UTF-8"));
JSONObject obj = new JSONObject();
try {
obj.put("BSSID", MAC);
obj.put("ESSID", Name);
obj.put("RSSID", Strength);
} catch (JSONException e) {
e.printStackTrace();
}
data = obj.toString();
writer.write(data);
writer.flush();
writer.close();
out_Stream.close();
InputStream in_Stream = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in_Stream, "ISO-8859-1"));
String line = "";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
in_Stream.close();
http.disconnect();
return result;
} catch (MalformedURLException e){
result = e.getMessage();
} catch (IOException e){
result = e.getMessage();
}
return result;
}
}
SendData class is perfectly working but problem is with for loop.
I think this is result that you are expecting :
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("1");
arrayList2.add("2");
arrayList2.add("3");
arrayList2.add("4");
arrayList2.add("5");
arrayList2.add("6");
arrayList2.add("6");
arrayList2.add("7");
arrayList2.add("8");
arrayList2.add("9");
arrayList2.add("10");
List<String[]> sarrayList = new ArrayList<>();
String[] arr = new String[3];
int i = 0;
for (int j = 0; j < arrayList2.size(); j++)
{
arr[i] = arrayList2.get(j);
i++;
if((j+1)%3==0)
{
sarrayList.add(arr);
i = 0;
arr = new String[3];
}
}
for(String [] sa:sarrayList)
{
for(String s:sa)
{
System.out.println(s);
}
System.out.println("=========");
}
This might not be the most efficient way of doing it. But it splits the ArrayList in to String arrays of length=3 and stores them in a new ArrayList named sarrayList
I would advise to use a datastructure to hold the record. See the code below this is a small example how you could do it
ArrayList<Record> records;
for (int i = 2; i < inputArrayList.size(); i = i + 3){
string ssid = namesArr.get(i - 2);
string bssid = namesArr.get(i - 1);
string rssid = namesArr.get(i);
records.add(new Record(ssid, bssid, rssid));
}
class Record{
string ssid;
string bssid;
string rssid;
// Constructor...
// Getter and setter to be implemented...
}
ok from what i understand you want to divide the arraylist each 3 elements thats how you do it with streams and it will return an a collection of arraylists each one has 3 elements
final int chunkSize = 3;
final AtomicInteger counter = new AtomicInteger();
//arrayList here us your array list
final Collection<List<String>> result = arrayList.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
and mentioning supermar10 answer you code make a class to map the strings to it like that
class Record{
string ssid;
string bssid;
string rssid;
Record(String ssid,String bssid,String rssid){
this.ssid=ssid;
this.bssid=bssid;
this.rssid=rssid;
}
}
now you have a class to map to now save the records in a list of Record
create a a list in the main class
static List<Record> lists=new ArrayList<>();
then map the data like that
result.stream().forEach(nowList -> saveRecord(nowList));
and thats the save method
static void saveRecord(List<String> list){
lists.add(new Record(list.get(0),list.get(1),list.get(2)));
}
I have simplified it to one loop and also modified insertValues so that it takes 3 more parameters. This
int size = arrayList2.size();
for (int j = 0; j < size; j += 3) {
if (size - j < 3 ) {
break;
}
String ssid = arrayList2.get(j);
String bssid = arrayList2.get(j + 1);
String rssid = arrayList2.get(j + 2);
insertValues(this, ssid, bssid, rssid);
}
if one the other hand ssid and so on are class variables the inside of the loop can be changed to
ssid = arrayList2.get(j);
bssid = arrayList2.get(j + 1);
rssid = arrayList2.get(j + 2);
insertValues();

How to convert a string contains array format to java array or list?

I have a string like this:
String res = '["A","B","0","1"]';
How to convert it to an array or list in Java to become like this:
String[] r = {"A","B","0","1"};
Since your string is a correct Json string, you may use the gson library:
String s = "[\"A\",\"B\",\"0\",\"1\"]";
Gson gson = new GsonBuilder().create();
String[] arr = gson.fromJson(s, String[].class);
// {"A","B","0","1"}
Without using Gson, You can get the desired result by following below approach -
String inputStr = "[\"A\",\"B\",\"0\",\"1\"]";
String[] strArray = inputStr.split("[^\\w\\d]");
List<String> list = new ArrayList<>();
for (String str : strArray) {
if (str != null && !str.isEmpty()) {
list.add(str);
}
}
System.out.println(list);
Output will be: [A, B, 0, 1]
String res = "[A,B,0,1]";
res = res.replace("[", "");
res = res.replace("]", "");
res = res.replaceAll(",", "");
String [] arrayOutput = new String [res.length()];
char [] ar = res.toCharArray();
for(int i = 0; i< ar.length; i++)
{
char buffer = ar[i];
arrayOutput[i] = String.valueOf(buffer);
}

Removed comma from last while working with StringBuilder

I've the following Java program and I don't want "," to be assign after my last element, what to do ?
String range = "400-450";
Integer startRange = null;
Integer endRange = null;
StringTokenizer st = new StringTokenizer(range,"-");
while(st.hasMoreTokens()) {
startRange = Integer.parseInt(st.nextToken());
endRange= Integer.parseInt(st.nextToken());
}
StringBuilder sb = new StringBuilder();
for (int i = startRange; i <= endRange; i++) {
sb.append(i).append(",");
}
System.out.println(sb);
The output should be
400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450 --> without comma at last
For Java 8 you could switch to new class StringJoiner which has beed added for exactly that purpose:
StringJoiner sb = new StringJoiner(",");
for (int i = startRange; i <= endRange; i++) {
sb.add(String.valueOf(i));
}
System.out.println(sb.toString());
Doing it manually, I'd suggest adding the comma before the item and then use substring(1):
for (int i = startRange; i <= endRange; i++) {
sb.append(",").append(i);
}
//Check for empty before!
System.out.println(sb.substring(1));
As #Jan says, use StringJoiner if you have Java8. Otherwise you could add a separator before the new entry and treat the first item differently by initialising the separator to blank.
String separator = "";
for (int i = startRange; i <= endRange; i++) {
sb.append(separator).append(i);
separator = ",";
}
This is the Java8 version
StringJoiner sb = new StringJoiner(",");
for (int i = startRange; i <= endRange; i++) {
sb.add(String.valueOf(i));
}
Just simple as
for (int i = startRange; i <= endRange; i++) {
sb.append(i);
if(i != endRange)
sb.append(",");
}
Use Joiner (guava) for Java < 8.
List<Integer> numbers = Lists.newArrayList(1, 3, 4, 5, 23);
System.out.println(Joiner.on(",").join(numbers));
And the output is:
1,3,4,5,23
Just let the last loop appending the commas stop before the last element is reached:
String range = "400-450";
Integer startRange = null;
Integer endRange = null;
StringTokenizer st = new StringTokenizer(range,"-");
while(st.hasMoreTokens()) {
startRange = Integer.parseInt(st.nextToken());
endRange= Integer.parseInt(st.nextToken());
}
StringBuilder sb = new StringBuilder();
// here, the "<=" was changed to "<"
for (int i = startRange; i < endRange; i++) {
sb.append(i).append(",");
}
// append last element
sb.append(endrange)
System.out.println(sb);
You are appending "," after each i
try to append "," only if you didn't reach the endRange
do:
for (int i = startRange; i <= endRange; i++) {
sb.append(i)
if (i != endRange)
sb.append(",");
}
this way "," will not be added to sb after last number.

Reverse every word in a string and capitalize the start of the word

Sample input:
abc def ghi
Sample output:
Cba Fed Ihg
This is my code:
import java.util.Stack;
public class StringRev {
static String output1 = new String();
static Stack<Character> stack = new Stack<Character>();
public static void ReverseString(String input) {
input = input + " ";
for (int i = 0; i < input.length(); i++) {
boolean cap = true;
if (input.charAt(i) == ' ') {
while (!stack.isEmpty()) {
if (cap) {
char c = stack.pop().charValue();
c = Character.toUpperCase(c);
output1 = output1 + c;
cap = false;
} else
output1 = output1 + stack.pop().charValue();
}
output1 += " ";
} else {
stack.push(input.charAt(i));
}
}
System.out.print(output1);
}
}
Any better solutions?
Make use of
StringBuilder#reverse()
Then without adding any third party libraries,
String originalString = "abc def ghi";
StringBuilder resultBuilder = new StringBuilder();
for (String string : originalString.split(" ")) {
String revStr = new StringBuilder(string).reverse().toString();
revStr = Character.toUpperCase(revStr.charAt(0))
+ revStr.substring(1);
resultBuilder.append(revStr).append(" ");
}
System.out.println(resultBuilder.toString()); //Cba Fed Ihg
Have a Demo
You can use the StringBuffer to reverse() a string.
And then use the WordUtils#capitalize(String) method to make first letter of the string capitalized.
String str = "abc def ghi";
StringBuilder sb = new StringBuilder();
for (String s : str.split(" ")) {
String revStr = new StringBuffer(s).reverse().toString();
sb.append(WordUtils.capitalize(revStr)).append(" ");
}
String strReversed = sb.toString();
public static String reverseString(final String input){
if(null == input || isEmpty(input))
return "";
String result = "";
String[] items = input.split(" ");
for(int i = 0; i < items.length; i++){
result += new StringBuffer(items[i]).reverse().toString();
}
return result.substring(0,1).toupperCase() + result.substring(1);
}
1) Reverse the String with this
StringBuffer a = new StringBuffer("Java");
a.reverse();
2) To make First letter capital use
StringUtils class in apache commons lang package org.apache.commons.lang.StringUtils
It makes first letter capital
capitalise(String);
Hope it helps.
Edited
Reverse the string first and make the first character to uppercase
String string="hello jump";
StringTokenizer str = new StringTokenizer(string," ") ;
String finalString ;
while (str.hasMoreTokens()) {
String input = str.nextToken() ;
String reverse = new StringBuffer(input).reverse().toString();
System.out.println(reverse);
String output = reverse .substring(0, 1).toUpperCase() + reverse .substring(1);
finalString=finalString+" "+output ;
}
System.out.println(finalString);
import java.util.*;
public class CapatiliseAndReverse {
public static void reverseCharacter(String input) {
String result = "";
StringBuilder revString = null;
String split[] = input.split(" ");
for (int i = 0; i < split.length; i++) {
revString = new StringBuilder(split[i]);
revString = revString.reverse();
for (int index = 0; index < revString.length(); index++) {
char c = revString.charAt(index);
if (Character.isLowerCase(revString.charAt(0))) {
revString.setCharAt(0, Character.toUpperCase(c));
}
if (Character.isUpperCase(c)) {
revString.setCharAt(index, Character.toLowerCase(c));
}
}
result = result + " " + revString;
}
System.out.println(result.trim());
}
public static void main(String[] args) {
//System.out.println(reverseCharacter("old is GlOd"));
Scanner sc = new Scanner(System.in);
reverseCharacter(sc.nextLine());
}
}

Duplicate entries inside loop of list<String>

I am using the following code and at the end i saw in calssEntries list the last values duplicated
i mean if i debug it i can see the right data but in the second iteration the values of the first data entries
are override and i see the second twice and so on
what i miss here?
String memberName = null;
String memberValue = null;
List<String> memberList = new ArrayList<String>();
List<String> memberValueList = new ArrayList<String>();+ArrayList<ClassEntry> calssEntries = new ArrayList<ClassEntry>();
...
while (dataRow != null) {
memberList.clear();
memberValueList.clear();
for (int i = 1; i < dataArray.length; i += 2) {
memberName = dataArray[i];
memberList.add(memberName);
memberValue = dataArray[i + 1];
memberValueList.add(memberValue);
}
ClassEntry classEntry = new ClassEntry();
classEntry.setClassName(className);
classEntry.setMemberName(memberList);
classEntry.setMemberValue(memberValueList);
calssEntries.add(classEntry);
....
I think the problem is that you need to create a new instance of memberList and memberValueList in the while loop. Something like:
calssEntries = new ArrayList<ClassEntry>();
...
while (dataRow != null) {
List<String> memberList = new ArrayList<String>();
List<String> memberValueList = new ArrayList<String>();
...
...
In your code, entries of calssEntries are referring to the same(single) instance of memberList and memberValue.
try this
for (int i = 1; i < dataArray.length; i += 2) {
int j = i;
memberName = dataArray[i];
memberList.add(memberName);
memberValue = dataArray[j + 1];
memberValueList.add(memberValue);
}

Categories