How to format array in string - java

I want to format log like this:
"order with orderid=1,orderid=2,orderid=3,orderid=4"
I have array with values [1,2,3,4].
I understand that it is enough easy to use loop for this but I want to know if there is tool in jdk (or library) which can do this.

Using java 8:
int[] n = new int[]{1,2,3,4};
String orders = Arrays.stream(n).mapToObj(i -> "orderid=" + i).collect(Collectors.joining(","));
String result = "order with " + orders;

You can easily build such a String using for-loop:
for (int i = 0; i < array.length; i++) {
//String append with orderid and array[i];
}

You can achieve this as below way,
public static void main (String[] args) throws java.lang.Exception
{
String strData[] = {"1","2","3"};
String result = Arrays.toString(strData); // OutPut [1,2,3]
result = result.substring(1, result.length() - 1); // OutPut 1,2,3
result = result.replaceAll(",", ", OrderId=");
System.out.println("Order with OrderId=" + result);
//OutPut Order with OrderId=1, OrderId=2
}

Related

(Java) Append elements to a String variable from String array up to specific index?

public class sample {
public static void main(String[] args) {
String[] test = new String[1024];
int count = 0;
test[count] = "33";
count++;
test[count] = "34";
String s = new String();
This is just a simplified version, but I would like to append elements to a String variable s up to the index value of count without using StringBuilder, is there a way to do it? Thank you.
edit: without using loop as well, is there a String manipulation function I can use?
One way to do that is using String.join and Arrays.copyOf:
String s = String.join("", Arrays.copyOf(test, count + 1));
Which, with your test data, produces 3334
Dont quite understand what you want...
But I guess you could user char array?
char[] c = new char[maxCount]
for(int i = 0;i<maxCount;i++){
c[i] = "34";
}
String s = String.valueOf(c)
Hope this could help you:)
Hard to say, what you're asking for...
Concatenating consecutive numbers could be easily done with a stream:
String s = IntStream.rangeClosed(0, 1024)
.mapToObj(Integer::toString)
.collect(Collectors.joining());
We can use the join function of String.
Assuming the test is the string array.
String joinedString = String.join("", Arrays.stream(test).limit(count).collect(Collectors.toList()))
You can use String.join()
public class Main {
public static void main(String[] args) {
String[] test = new String[1024];
int count = 0;
test[count] = "33";
count++;
test[count] = "34";
String s = new String();
System.out.println(s=String.join("", Arrays.copyOf(test, count + 1)));
}
}

Is there an easy way to eliminate the final comma in my output? Number Seperator

For another assignment i needed to program a "number seperator", that splits any given int value into all of its digits and returns it to the main class as a String.
I have the program up and running but there's a small problem with my output.
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
System.out.println("Input a Number: ");
int zahl = readInt();
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
System.out.print(ziffern.charAt(i) + ",");
}
}
}
The output of 1234 should be: 1,2,3,4
and the actual output is: 1,2,3,4,
At the risk of sounding extremely stupid, is there an easy fix to this?
How about printing first element without comma and rest in form ,nextElement like
one, two, three
^^^---------------- - before loop
^^^^^----------- - loop iteration
^^^^^^^---- - loop iteration
It can be achieved like:
if(ziffern.length()>0){
System.out.print(ziffern.charAt(0));
}
for(int i=1; i<ziffern.length(); i++){
System.out.print(", "+ziffern.charAt(i));
}
OR you can convert ziffern to String[] array first and use built-in solution which is: String.join(delimiter, data)
System.our.print(String.join(",", ziffern.split("")));
When it's the last iteration, just don't add it.
In the last iteration, it will make the comma empty so that you won't see it after the last value.
String comma=",";
for (int i = 0; i < ziffern.length(); i++) {
if (i == ziffern.length()-1) {
comma="";
}
System.out.print(ziffern.charAt(i) + comma);
}
with Java 8 and streams you can do it in a single command:
String join = Arrays.asList(ziffern.split(""))
.stream()
.collect(Collectors.joining(","));
System.out.println(join);
or with just plain java 8:
String join = String.join(",", ziffern.split(""));
System.out.println(join);
A simple one liner will do your job:
static String splitNumber(int zahl) {
return String.join(",", String.valueOf(zahl).split(""));
}
Quite often this occurs when you know you have at least two items to print. So here is how you could do it then.
String ziffern = splitNumber(zahl);
String output = ziffern[0];
for (int i = 1; i < ziffern.length(); i++) {
output = "," + ziffern[i];
}
System.out.println(output);
You can just output the string without the last character.
Your modified code should be:
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
int zahl = 1234;
String s="";
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
s+=ziffern.charAt(i) + ",";
}
System.out.println(s.substring(0,s.length()-1));
}

How to convert/sort a String based on two symbols in Java?

I have the following string:
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
And I'm trying to convert it to:
String converted = "aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz";
To be somehow sorted. This is what I have tried so far:
String[] parts = string.split("\\n");
List<String[]> list = new ArrayList<>();
for(String part : parts) {
list.add(part.split(","));
}
for(int i = 0, j = i + 1, k = j + 1; i < list.size(); i++) {
String[] part = list.get(i);
System.out.println(part[i]);
}
So I managed to get first element from each "unit" separately. But how to get all and order them so I get that result?
Can this be even simpler using Java8?
Thanks in advance!
I guess one way to do it would be:
String result = Arrays.stream(string.split("\\n"))
.map(s -> {
String[] tokens = s.split(",");
Arrays.sort(tokens);
return String.join(",", tokens);
})
.collect(Collectors.joining("\\n"));
System.out.println(result); // aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz
Just notice that in case your patterns are more complicated than \n or , - it is a good idea to extract those an separate Pattern(s)
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
String converted = Arrays.stream(string.split("\\n"))
.map(s -> Arrays.stream(s.split(","))
.sorted()
.collect(Collectors.joining(",")))
.collect(Collectors.joining("\\n"));
You can have it the old fashioned way without the use of Java 8 like this:
public static void main(String[] args) {
String s = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
System.out.println(sortPerLine(s));
}
public static String sortPerLine(String lineSeparatedString) {
// first thing is to split the String by the line separator
String[] lines = lineSeparatedString.split("\n");
// create a StringBuilder that builds up the sorted String
StringBuilder sb = new StringBuilder();
// then for every resulting part
for (int i = 0; i < lines.length; i++) {
// split the part by comma and store it in a List<String>
String[] l = lines[i].split(",");
// sort the array
Arrays.sort(l);
// add the sorted values to the result String
for (int j = 0; j < l.length; j++) {
// append the value to the StringBuilder
sb.append(l[j]);
// append commas after every part but the last one
if (j < l.length - 1) {
sb.append(", ");
}
}
// append the line separator for every part but the last
if (i < lines.length - 1) {
sb.append("\n");
}
}
return sb.toString();
}
But still, Java 8 should be preferred in my opinion, so stick to one of the other answers.
The Pattern class gives you a possibility to stream directly splitted Strings.
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
Pattern commaPattern = Pattern.compile(",");
String sorted = Pattern.compile("\n").splitAsStream(string)
.map(elem -> commaPattern.splitAsStream(elem).sorted().collect(Collectors.joining(",")))
.collect(Collectors.joining("\n"));

how to get string value in java

String Qty1 = "1";
String Qty2 = "2";
String qtyString = "", bString = "", cString = "";
for(int j = 1; j <= 2; j++)
{
qtyString = String.valueOf(("Qty" + j));
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = Qty1;
qtyString = Qty2;
I would like to get qtyString = 1, qtyString = 2; I want to print Qty1 and Qty2 value in my for loop. In C#, this code works correctly. I don't know how to get qtyString value as 1, 2 in java.
You should use array of strings for this purpose.
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
String array is needed if you want to print a list of string:
String[] Qty = {"1", "2"};
String qtyString = null;
for (int j = 0; i<=1; j++) {
qtyString = Qty[j];
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = 1
qtyString = 2
I don't know for sure what you're trying to do, and you've declared Qty1 twice in your code. Assuming the second one is supposed to be Qty2, then it looks like you're trying to use string operations to construct a variable name, and get the value of the variable that way.
You cannot do that in Java. I'm not a C# expert, but I don't think you can do it in C# either (whatever you did that made you say "it works in C#" was most certainly something very different). In both those languages and in all other compiled languages, the compiler has to know, at compile time, what variable you're trying to access. You can't do it at runtime. (Technically, in Java and C#, there are ways to do it using reflection, depending on how and where your variables are declared. But you do not want to solve your problem that way.)
You'll need to learn about maps. Instead of separate variables, declare a Map<String, String> that maps the name that you want to associate with a value (Qty1, Qty2) with the value (which is also a String in this case, but could be anything else). See this tutorial for more information. Your code will look something like
Map<String, String> values = new HashMap<>();
values.put("Qty1", "1");
values.put("Qty2", "2");
...
qtyString = values.get("Qty"+j);
(Actually, since your variable name is based on an integer, an array or ArrayList would work perfectly well too. Using maps is a more general solution that works in other cases where you want names based on something else beside sequential integers.)
Try this examples:
With enhanced for-loop and inline array:
for(String qty : new String[]{"1", "2"})
System.out.printf("qtyString = %s\n", qty);
With enhanced for-loop and array:
String [] qtys = {"1", "2"};
for(String qty : qtys)
System.out.printf("qtyString = %s\n", qty);
Using for-loop and array:
String [] qty = {"1", "2"};
for(int i = 0; qty.length > i; i ++)
System.out.printf("qtyString = %s\n", qty[i]);
you can try this for java:
static String Qty[] = {"1", "2"} ;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
}
And For Android:
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}

How do I print a 2d array?

My array is:
String[][] name = new String[15][2];
int rowNumber = 0;
My add button is:
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
I do not know what to put in my list button (lists the first name and last name) into my TextArea called outPut.
The Whole Code:
`
public class StudentGradesView extends FrameView {
String[][] name = new String[15][2];
double[][] testMark = new double[15][4];
int rowNumber = 0;
private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
rowNumber ++;
}
private void btnListMouseClicked(java.awt.event.MouseEvent evt) {
String outputStr = "";
for(int i=0; i < rowNumber; i++) {
outputStr += name[rowNumber][0] + " " + name[rowNumber][1] + "\n";
}outPut.setText(outputStr);
}
}`
Okay, I think I get what you want now.
First we take the inputs...
name[numberOfInputs][0] = firstName.getText();
name[numberOfInputs][1] = lastName.getText();
numberOfInputs += 1;
Now you want to output this to a textarea...
String outputStr = "";
for(int i=0; i < numberOfInputs; i++) {
outputStr += name[i][0] + " " + name[i][1] + "\n";
}
Then set your output textarea
outPut.setText(outputStr);
You are getting nulls because you are specifying a static array size but you (probably) are not filling up the array with test cases up to that amount. So you are printing elements of the array that are simply not populated.
Edit: for comments.
String st = "";
for (int i = 0; i < 15; i++)
st += name[i][0] + " " + name[i][1] + "\n";
outPut.setText(value);
This loops over the array and creates a string containing all the full names, separated by a line break.
This then sets the text using outPut.setText(value);
for(String[] s1d : s2d)
for(String s : s1d)
System.out.println(s);
A simple way using for() construct
The easiest way to print any array to any depth is to use Arrays.deepToString():
System.out.println(Arrays.deepToString(array));
try this:
import java.util.Arrays;
.
.
.
String[][] a = { { "john" },
{ "jones" }
};
System.out.println(Arrays.deepToString(a)); //whole string array
System.out.println(Arrays.deepToString(a[0])); //john
System.out.println(Arrays.deepToString(a[1])); //jones

Categories