How to get values from ArrayList<String[]> - java

How to get or print String from ArrayList<String[]>?
ArrayList<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"A1","A1","A3"});
arrayList.add(new String[]{"B1","B1","B3"});
arrayList.add(new String[]{"C1","C1","C3"});
System.out.println("*** 1 ***");
System.out.println(arrayList);
System.out.println("*** 2 ***");
for (int i = 0; i < arrayList.size(); i++) {
System.out.println((String[])arrayList.get(i));
}
System.out.println("*** 3 ***");
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(arrayList.get(i).toString());
}
System.out.println("*** 4 ***");
for (int i = 0; i < arrayList.size(); i++) {
String[] strings = arrayList.get(i);
System.out.println(strings);
}
output:
*** 1 ***
[[Ljava.lang.String;#2a85f3d6, [Ljava.lang.String;#404b7c69, [Ljava.lang.String;#1bd4f279]
*** 2 ***
[Ljava.lang.String;#2a85f3d6
[Ljava.lang.String;#404b7c69
[Ljava.lang.String;#1bd4f279
*** 3 ***
[Ljava.lang.String;#2a85f3d6
[Ljava.lang.String;#404b7c69
[Ljava.lang.String;#1bd4f279
*** 4 ***
[Ljava.lang.String;#2a85f3d6
[Ljava.lang.String;#404b7c69
[Ljava.lang.String;#1bd4f279

Sadly, java's default toString() for arrays is useless. You must use the utility method Arrays.toString(). This will work:
for (String[] strings : arrayList)
System.out.println(Arrays.toString(strings));

In Java, each object has toString() method, the default is displaying the class name representation, then adding # and then the hashcode.
strings is an array of Strings. You should use Arrays#toString(), which is implemented this way (I advise you to go through it to better understand what's going on):
3860 public static String toString(int[] a) { {
3861 if (a == null)
3862 return "null";
3863 int iMax = a.length - 1;
3864 if (iMax == -1)
3865 return "[]";
3866
3867 StringBuilder b = new StringBuilder();
3868 b.append('[');
3869 for (int i = 0; ; i++) {
3870 b.append(a[i]);
3871 if (i == iMax)
3872 return b.append(']').toString();
3873 b.append(", ");
3874 }
3875 }
Or, you can loop on it and manually print the items:
for(String str: strings) {
System.out.println(str + " ");
}

Try to modify this :
**#Override
public String toString() {
return "abc [name=" + name + ", stage=" + stage
+ ", messageCode=" + messageCode + ", title=" + title
+ ", description=" + description + ", expiryTimeLeft="
+ expiryTimeLeft + ", holdLimit=" + holdLimit + ", points="
+ points];
}

Related

How can I generated a list of data then query into the list?

I am new to Java and I am trying to build a Java command-line program, which generates random dataset (as in getData()) and query into the generated dataset. But I don't know how to pass the generated data from getData() function to the main function so that I can find the oldest person in my generated data.
public class Data {
public String first;
public String last;
public int age;
public int id;
public String country;
public Data(String first, String last, int age, int id, String country) {
this.first = first;
this.last = last;
this.age = age;
this.id = id;
this.country = country;
}
public String toString() {
return "{" +
" 'firstName': " + first + "," +
" 'lastName': " + last + "," +
" 'age': " + age + "," +
" 'id': " + id + "," +
" 'country': " + country +
" }";
}
public static ArrayList<Data> getData(int numRows) {
ArrayList<Data> generator = new ArrayList<>();
String[] names = {"James", "Matt", "Olivia", "Liam", "Charlotte", "Amelia", "Evelyn", "Taeyeon", "Sooyoung", "Tiffany", "Yoona", "Hayley"};
String[] lastName = {"Novak", "Forbis", "Corner", "Broadbet", "Kim", "Young", "Hwang", "Choi", "McDonalds", "Kentucky", "Holmes", "Shinichi"};
String[] country = {"New Zealand", "Vietnam", "Korea", "French", "Japan", "Switzerland", "Italy", "Spain", "Thailand", "Singapore", "Malaysia", "USA"};
String data = "";
Random ran = new Random();
int namesLength = numRows; // passing length to names_len
int lastNameLength = lastName.length; // passing length to lastname_len
int countryLength = country.length; // passing length to lastname_len
for (int i = 0; i < numRows; i++) { // for loop to iterate upto names.length
int x = ran.nextInt(namesLength); // generating random integer
int y = ran.nextInt(lastNameLength); // generating random integer
int z = ran.nextInt(countryLength);
int a = ran.nextInt(40);
int exampleId = ran.nextInt(1000);
// below for loop is to remove that element form names array
for (int j = x; j < (namesLength - 1); j++) {
names[j] = names[j + 1]; // this moves elements to one step back
}
// below for loop is to remove that element form Lastnames array
for (int j = y; j < (lastNameLength - 1); j++) {
lastName[j] = lastName[j + 1]; // this moves elements to one step back
}
for (int j = z; j < (countryLength - 1); j++) {
country[j] = country[j + 1]; // this moves elements to one step back
}
namesLength = namesLength - 1; // reducing len of names_len by 1
lastNameLength = lastNameLength - 1; // reducing len of lastname_len by 1
countryLength = countryLength - 1; // reducing len of lastname_len by 1
// Output data in NDJSON format
data = "{" +
" 'firstName': " + names[x] + "," +
" 'lastName': " + lastName[y] + "," +
" 'age': " + a + "," +
" 'id': " + exampleId + "," +
" 'country': " + country[z] +
" }";
System.out.println(data);
// How can I add data to the generator list, the generator.add(data) does not work
}
// return a list of data
return generator;
}
public static void main(String[] args) {
// Generate random data
int rows = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows (maximum 12) you want to generate: ");
rows = sc.nextInt();
while (rows >= 13 || rows <= 0) {
System.out.println("Rows must be in range of 1 and 12");
System.out.print("Please reenter the number of rows: ");
rows = sc.nextInt();
}
System.out.println("Data is now generated");
ArrayList<Data> generatedData = getData(rows);
String[] base_options = {
"1 - Find the oldest person",
"2 - Group by country and return count",
"3 - Choose a country and group by age range",
"4 - Find the youngest person",
};
System.out.println(base_options);
// Task 2
// TODO: PASTE GENERATED DATA INTO THIS
// Find oldest
Data oldest = generatedData.stream().max((a,b) -> a.age - b.age).get();
System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
generator.add(new Data(names[x], lastName[y], a, exampleId, country[z])); works for me just fine
You can parse your generated data in string to Data and get the max valud like this:
public static void main(String[] args) {
// Generate random data
int rows = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows (maximum 12) you want to generate: ");
rows = sc.nextInt();
while (rows >= 13 || rows <= 0) {
System.out.println("Rows must be in range of 1 and 12");
System.out.print("Please reenter the number of rows: ");
rows = sc.nextInt();
}
System.out.println("Data is now generated");
ArrayList<String> generatedData = getData(rows);
// Find oldest
Data oldest = generatedData
.stream()
.map(it -> extractData(it))
.max(Comparator.comparingInt(a -> a.age))
.get();
System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
}
private static Data extractData(String str) {
return new Data(
extractProperty(str, "firstName"),
extractProperty(str, "lastName"),
Integer.parseInt(extractProperty(str, "age")),
Integer.parseInt(extractProperty(str, "id")),
extractProperty(str, "country")
);
}
private static String extractProperty(String str, String keyName) {
String key = "'" + keyName + "': ";
int startIndex = str.indexOf(key) + key.length();
if (startIndex < 0) {
return "";
}
StringBuilder value = new StringBuilder();
for (int i = startIndex ; i < str.length() ; ++i) {
char ch = str.charAt(i);
if (ch == ',') {
break;
}
value.append(ch);
}
return value.toString();
}

How can i have output that write different or missing element in array?

When I run this, I can see exact result "false" but I also want to see what difference there is. For instance
"ozer and gunthy" match but "albundy and aldy" does not
package start;
public class Start {
public static void main(String[] args) {
String[] a = {"ozer + gunthy + albundy"};
String[] b = {"ozer + günthy + aldy"};
boolean b1 = false;
if (a.length != b.length){
b1 = false;
}else {
for (int i = 0; i < a.length; i++){
if (a[i] == b[i]){
b1 = true;
}else {
b1 = false;
break;
}
}
}
System.out.println(b1);
}
}
You will want to replace
a[i] == b[i]
with
a[i].equals(b[i])
You will also need to fix your arrays
public static String[] list1 = {"ozer", "gunthy","albundy"};
public static String[] list2 = {"ozer", "günthy","aldy"};
then, you will need to write and call a method to properly analyze the arrays to your specification:
public String methodName(String[] list1, String[] list2)
{
String output = "";
if (list1.length != list2.length)
{
return "The Arrays differ in length";
}
else
{
for (int i = 0; i < list1.length; i++)
{
if (list1[i].equals(list2[i]))
{
output += "" + list1[i] + " is equal to " + list2[i] + "\n";
}
else
{
output += "" + list1[i] + " is not equal to " + list2[i] + "\n";
}
}
}
return output;
}

comparing two arrayLists for match a condition for postprocessing

I have two arraylists
ArrayList A ArrayList B
London 001
Berlin 001
Frankfurt 450
Rome 001
Geneva 230
Lille 620
What, I am trying to print out is the following:
If, the code in the arraylist are not equal then add separate XML tags to it. if they are equal then club them in a single tag.
E.g
<001> London Berlin </001> <450> Frankfurt </450> <001> Rome </001> <230> Geneva </230> <620> Lille </620>
Below is the logic which I am using
List<String> newList = new ArrayList<String>();
for(int i= 0; i< ListA.size(); i++){
if(i >=1){
String temp = ListB.get(i-1);
if(temp.contentEquals(ListB.get(i)))
{
newList.add(ListA.get(i));
}
else{
newList.add("<"+ ListB.get(i) +"> " + ListA.get(i) + " </"+ ListB.get(i) +">" );
}
}
else{
/*if i=0*/
newList.add("<"+ ListB.get(i) +"> " + ListA.get(i) + " </"+ ListB.get(i) +">" );
}
}
StringJoiner outputText = new StringJoiner(" ");
for(int i=0; i< newList.size();i++){
outputText.add(newList.get(i));
}
System.out.println(outputText.toString());
}
I understand there is a problem with the logic. Just got lost in loops.
your logic was wrong, try this one:
for (int i = 0; i < ListA.size(); i++) {
if (i == 0) {
newList.add("<" + ListB.get(i) + "> " + ListA.get(i) + " ");
}
if (i >= 1) {
String temp = ListB.get(i - 1);
if (temp.equals(ListB.get(i))) {
newList.add(ListA.get(i));
} else {
newList.add("</" + ListB.get(i - 1) + ">" + " <" + ListB.get(i) + "> " + ListA.get(i) + " ");
}
}
if (i == ListA.size() - 1) {
newList.add("</" + ListB.get(i) + ">");
}
}
by using this logic you will have exactly the desired output
see below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MultipleLists {
public static void main(String[] args) {
// London 001
// Berlin 001
// Frankfurt 450
// Rome 001
// Geneva 230
// Lille 620
List<String> cities = Arrays.asList("London", "Berlin", "Frankfurt", "Rome", "Geneva", "Lille");
List<String> codes = Arrays.asList("001", "001", "450", "001", "230", "620");
List<CityCode> cityCodes = new ArrayList<>();
for (int i = 0; i < cities.size(); i++) {
cityCodes.add(new CityCode(cities.get(i), codes.get(i)));
}
StringBuffer stringBuffer = new StringBuffer();
Collections.sort(codes);
Set<String> codesSet = new HashSet<>(codes);
for (String code : codesSet) {
stringBuffer.append("<" + code + ">");
for (CityCode cityCode : cityCodes) {
if (cityCode.getCode().compareTo(code) == 0) {
stringBuffer.append(cityCode.getName());
stringBuffer.append(" ");
}
}
stringBuffer.append("</" + code + ">");
}
System.out.println(stringBuffer); // <001>London Berlin Rome </001><620>Lille </620><230>Geneva </230><450>Frankfurt </450>
}
}
class CityCode {
private String name;
private String code;
public CityCode(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
}
You need to make a minor change and that is to add the closing tags differently. Other code remains the same.
List<String> newList = new ArrayList<String>();
for(int i= 0; i< ListA.size(); i++){
if(i >=1){
String temp = ListB.get(i-1);
if(temp.contentEquals(ListB.get(i)))
{
newList.add(ListA.get(i));
}else{
newList.add(" </"+ ListB.get(i-1) +">" )
newList.add("<"+ ListB.get(i) +"> " + ListA.get(i) );
}
}else{
/*if i=0*/
newList.add("<"+ ListB.get(i) +"> " + ListA.get(i) + );
}
if(i==ListA.size()-1){
newList.add(" </"+ ListB.get(i-1) +">"
}
}
StringJoiner outputText = new StringJoiner(" ");
for(int i=0; i< newList.size();i++){
outputText.add(newList.get(i));
}
System.out.println(outputText.toString());
}
Hope it helps.
Something like this?
public static void main(String[] args) {
List<String> cities = Arrays.asList("London", "Berlin", "Frankfurt", "Rome", "Geneva", "Lille");
List<String> codes = Arrays.asList("001", "001", "450", "001", "230", "620");
Map<String, List<String>> result = new HashMap<>();
for (int i = 0; i < cities.size(); i++) {
String city = cities.get(i);
String code = codes.get(i);
if (result.containsKey(code)) {
List<String> list = result.get(code);
list.add(city);
} else {
ArrayList<String> mappedCities = new ArrayList<>();
mappedCities.add(city);
result.put(code, mappedCities);
}
}
String fullXml = result.entrySet().stream().parallel().map(entry -> {
String tag = entry.getKey();
List<String> vals = entry.getValue();
String citiesSeparated = vals.stream().collect(Collectors.joining(" "));
return xmlStart(tag) + citiesSeparated + xmlEnd(tag);
}).collect(Collectors.joining(" "));
System.out.println(fullXml);
}
private static String xmlEnd(String s) {
return "<" + s + "/>";
}
private static String xmlStart(String s) {
return "<" + s + ">";
}
First of all: having two disconnected Lists is not a good idea (very bad idea).
You highly depend on position of code and city in them. Maybe you can reconsider to use a Map instead? It will be much easier.
Second: it seems like you missed one requirement which is in your code.
"Join cities in one tag if code is equal to previous city code"
is it true or not? Why "Rome" with code 001 is in separate tag from "London Berlin"?
Third: Of course Jose's answer is correct OO answer which personally I prefer.
Forth: BTW if "Rome" must be in the same tag as "London Berlin" you can simply use a Map like:
Map<String,String> codeCityMap = new TreeMap<String,String>();
for (int i=0;i <arrayListA.size();i++)
{
String cities = codeCityMap.get(arrayListB.get(i));
cities = null == cities?arrayListA.get(i):cities + " " + arrayListA.get(i);
codeCityMap.put(arrayListB.get(i), cities);
}
List<String> newList = new ArrayList<String>();
for (String code: codeCityMap.keySet())
{
newList.add("<" + code + ">" + codeCityMap.get(code) + "</" + code + ">");
}
If "Rome" must not be you can use same technique, but introduce a little additional code to check also equality to to the previous citiy code in the line cities = null == cities?arrayListA.get(i):cities + " " + arrayListA.get(i);
if you need to main order or sort result use LinkedMap, TreeMap or do it on your own.

Run a for loop until the String Condition in JAVA

If I have a String array as follows.
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
I want to copy all the contents from between "H ---- " to " ---- ". That is it should be "SinghSawhRaman" (excluding "H ---- " and " ---- ".
Something like this:
String keywords = "";
int j = 0;
for(int i = 0; i < name.length; i++){
if(name[i].contains("H ---- ")){
for(j = i; j < 5; j++){
// There problem is j < 5. I want to give a condition when name[i].contains(" ---- ")
// but not sure how should I be able to do it.
keywords = keywords + name[j];
}
Can someone please show me the best way to do this?
for(j = i; !name[j].contains(" ---- "); j++){
keywords = keywords + name[j];
}
That should work for you, you can set the break condition of a for loop to be any boolean expression.
Edit: Need the ! in there as loop breaks when condition is false.
Any reason that you use contains instead of equals ?
If using equals is also fine for you, you could use a List :
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
List<String> s = Arrays.asList(name);
StringBuilder sb = new StringBuilder();
for(int i = s.indexOf("H ---- ")+1; i < s.indexOf(" ---- "); i++)
sb.append(s.get(i));
System.out.println(sb);
I would do it like so
private static String copyFrom(String[] in, String begin, String end) {
StringBuilder sb = new StringBuilder();
boolean start = false;
if (in != null) {
for (String s : in) {
if (!start) {
start = s.equals(begin);
} else {
start = !s.equals(end);
if (start) {
sb.append(s);
}
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String[] name = {"aval", "H ---- ", "Singh", "Sawh",
"Raman", " ---- ", "parminder", "kaur",
"jaspreet", "asneet", " ---- "};
String keywords = copyFrom(name, "H ---- ", " ---- ");
System.out.println(keywords);
}
Outputs
SinghSawhRaman
String keywords = "";
boolean append = false;
for(j = 0; j <= name.length; j++) {
if(name[j].contains("H----")
append = true;
if(append)
keywords += name[j];
if(name[j].contains("----") {
append = false;
break;
}
}
Notice that, if you move the if(name[j].contains("H----") block below the if(append) block, you will exclude the H--- from the keywords string;
Simply break out of the outer loop once your condition has been reached:
boolean capture = false;
for (String n : name) {
if (n.contains("H ---- ")) {
capture = true;
} else if (n.contains(" ---- ")) {
break;
} else if (capture) {
keywords = keywords + n;
}
}
If there are multiple occurrences of H ---- and ----, then don't break out of the loop, but simply set capture = false instead of break.
With two nested loops, you will be reading any elements that make up part of a name twice, which is inefficient. Unless it is possible to have names with nested H ----, you are better off removing the inner loop.
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
String key ="";
boolean flag = false;
for(String s : name){
if(s.equals("H ---- ")){
flag = true;
}
if(s.equals(" ---- ")){
flag = false;
}
if(flag && !s.equals("H ---- ")){
key+=s;
}
}
System.out.println(key);

Why are these array elements null?

I have an array which has been initialised with another.
a1 = a2; //right hand side is actually a method returning an array
I can append the returned array elements to a JTextArea but printing them out produces null in the console.
for (int i = 0; i < a1.lenght; i++) {
outputTextArea.append(a1[i]);
System.out.println(a1[i]);
}
Why is this? Thank you.
This is the method:
public String[] searchString(ArrayList<String> content, String string){
stringArray = new String[content.size()];
for(int i = 0; i < content.size(); i++){
if(string.equals(content.get(i))){
if(content.indexOf(string) == 0) {
stringArray[i] = content.get(i) + " " + content.get(i+1) + "\n";
} else if ((content.indexOf(string) > 0) && (content.indexOf(string) < (content.size()-1))) {
stringArray[i] = content.get(i-1) + " " + content.get(i) + " " + content.get(i + 1) + "\n";
} else if ((content.indexOf(string)) == (content.size()-1)) {
stringArray[i] = content.get(i -1) + " " + content.get(i);
}
}
}
return stringArray;
}
The Output NULL not from a1 but from a2
you have if statement :
if (string.equals(content.get(i))) {
.....
}
without else , so if the string != content.get(i) , so it will return null in this index at (a2)
so you may need to initialize a2 with values , or make check like this : if(a1[i] != null)
for(int i = 0; i < a1.lenght; i++){
if(a1[i]!=null){///////////to avoid the null values
outputTextArea.append(a1[i]);
System.out.println(a1[i]);
}
}
the second problem you will face in this code (When you repeated your string in content array):
stringArray[i] = content.get(i) + " " + content.get(i + 1) + "\n";
if i = content.size() ,so ( i+1 ) will IndexOutOfBoundsException

Categories