Java converting object array to string array - java

So i've been trying to solve this issue for hours but cant seem to find an answer which would work.
i have an object array which stores flight information and i had to remove flights which had Valstybe: "Maldyvai"
so i made a new object array without them, but when i try to print it i get a memory location.
How do i convert the object array to string array?
even though i have a tostring method in my java class
package com.company;
import java.util.*;
import com.company.Isvestine.OroUostasKeleivis;
public class Main {
public static void main(String[] args) {
// write your code here
OroUostasKeleivis Keleiviai1 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5465);
OroUostasKeleivis Keleiviai2 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5466);
OroUostasKeleivis Keleiviai3 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5467);
OroUostasKeleivis Keleiviai4 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5468);
OroUostasKeleivis Keleiviai5 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5469);
OroUostasKeleivis Keleiviai6 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5470);
OroUostasKeleivis Keleiviai7 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5475);
OroUostasKeleivis Keleiviai8 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5476);
OroUostasKeleivis Keleiviai9 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5477);
OroUostasKeleivis Keleiviai10 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5488);
OroUostasKeleivis[] keleiviai = new OroUostasKeleivis[10];
keleiviai[0] = Keleiviai1;
keleiviai[1] = Keleiviai2;
keleiviai[2] = Keleiviai3;
keleiviai[3] = Keleiviai4;
keleiviai[4] = Keleiviai5;
keleiviai[5] = Keleiviai6;
keleiviai[6] = Keleiviai7;
keleiviai[7] = Keleiviai8;
keleiviai[8] = Keleiviai9;
keleiviai[9] = Keleiviai10;
for (OroUostasKeleivis keleiveliai:keleiviai) {
System.out.println(keleiveliai);
}
System.out.println("test debug");
OroUostasKeleivis[] keleiviaibemaldyvu = new OroUostasKeleivis[10];
for (int i = 0; i < 10; i++) {
}
System.out.println(IsstrintiMaldyvus(keleiviai));
String convertedStringObject = IsstrintiMaldyvus(keleiviai) .toString();
System.out.println(convertedStringObject );
}
static Object[] IsstrintiMaldyvus(OroUostasKeleivis[] keleiviai){
OroUostasKeleivis[] keleiviaiBeMaldyvu = new OroUostasKeleivis[10];
int pozicija = 0;
for ( OroUostasKeleivis keleiveliai: keleiviai) {
if (keleiveliai.getValstybe() != "Maldyvai"){
keleiviaiBeMaldyvu[pozicija] = keleiveliai;
pozicija++;
}
}
return keleiviaiBeMaldyvu;
}
}

but when i try to print it i get a memory location
Yes, you will NOT have result as you expected, especially calling toString() with any array. See documentation of java.lang.Object.toString() for more details.
So how can we solve problem?
first, override toString() method in OroUostasKeleivis like this:
class OroUostasKeleivis {
#Override
public String toString() {
// your implementation here
return null; // TODO: change here
}
}
Second, you may do either way:
If you're interested in just print out, you can do that with System.out.println(keleiveliai) in for-each loop like you do.
If you're interested in converting OroUostasKeleivis[] to String[], you can:
// this requires Java 8 or later
String[] converted = Arrays.asList(keleiviai)
.stream()
.map(OroUostasKeleivis::toString)
.toArray(String[]::new);
// then use `converted`

Use System.out.println(Arrays.toString(IsstrintiMaldyvus(keleiviai)))
https://www.geeksforgeeks.org/arrays-tostring-in-java-with-examples/
It will print the array contents similar to how ArrayList would get printed if it had the same content.
Think of it as:
[ obj1.toString(), obj2.toString(), ... ]

Using java.util.Arrays#stream(T[]) filter and convert object array to string array and use java.util.Arrays#toString(java.lang.Object[]) convert array to readable string.
final String[] oroUostasKeleivis = Arrays.stream(keleiviai)
.filter(
k -> k.getValStybe() != "Maldyvai"
)
// or other convert code
.map(OroUostasKeleivis::toString)
.toArray(String[]::new);
System.out.println(Arrays.toString(oroUostasKeleivis));

Related

String cannot be added to List using Object in Java

I am working on a JSF based Web Application where I read contents from a file(dumpfile) and then parse it using a logic and keep adding it to a list using an object and also set a string using the object. But I keep getting this error. I am confused where I am wrong. I am a beginner so can anyone be kind enough to help me?
List<DumpController> FinalDumpNotes;
public List<DumpController> initializeDumpNotes()
throws SocketException, IOException {
PostProcessedDump postProcessedDump = (PostProcessedDump) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("postProcessedDump");
List<DumpController> FinalNotes = new ArrayList<>();
if (postProcessedDump.getDumpNotes() == null) {
dumpNotes = new DumpNotes();
}
DumpListController dlcon = (DumpListController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dumpListController");
DumpInfo dumpinfo = dlcon.getSelectedDumpInfo();
String fileName = dumpinfo.getDate() + dumpinfo.getTime() + dumpinfo.getSeqNo() + dumpinfo.getType() + dumpinfo.getTape() + dumpinfo.getDescription() + ".txt";
if (checkFileExistsInWin(fileName)) {
postProcessedDump.setDumpnotescontent(getFileContentsFromWin(fileName));
String consolidateDumpnotes = getFileContentsFromWin(fileName);
String lines[];
String content = "";
lines = consolidateDumpnotes.split("\\r?\\n");
List<String> finallines = new ArrayList<>();
int k = 0;
for (int i = 0; i < lines.length; i++) {
if (!lines[i].equalsIgnoreCase("")) {
finallines.add(lines[i]);
k++;
}
}
for (int j = 0; j < finallines.size(); j++) {
if (finallines.get(j).startsWith("---------------------SAVED BY")) {
PostProcessedDump dump = new PostProcessedDump();
dump.setDumpMessage(content);
content = "";
FinalDumpNotes.add(dump);
} else {
content = content + finallines.get(j);
}
}
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("postProcessedDump", postProcessedDump);
return FinalDumpNotes;
}
I get the following error:
If you want to add instances of type PostProcessedDump to your List you should change it's type. Also, don't forget to initialize it. Something like,
List<PostProcessedDump> FinalDumpNotes = new ArrayList<>();
Also, Java naming convention is to start variable names with a lower case letter. FinalDumpNotes looks like a class, I would suggest something like
List<PostProcessedDump> processedList = new ArrayList<>();
Problems with your code:
List<DumpController> FinalDumpNotes;
You declare FinalDumpNotes to be a List of DumpController objects, but you never initialize it. In addition, your IDE is barfing on the following line of code:
FinalDumpNotes.add(dump);
because you are attempting to add a PostProcessedDump object to the List instead of a DumpController object.
For starters, you need to initialize your list like this:
List<DumpController> finalDumpNotes = new ArrayList<DumpController>();
Notice that I have made the variable name beginning with lower case, which is the convention (upper case is normally reserved for classes and interfaces).
I will leave it to you as a homework assignment to sort out the correct usage of this List.

String[] from ArrayList<Class>

I recently started working on an app that does a request to a server and gets a json response.
The "thing" functioned beautifully until i had to implement new stuff in the list and now i have a hard time to fix it.
Any help is very appreciated:
class RemoteConfig
{
// names and type must match what we get from the remote
String[] username;
ArrayList<accDetails> in_groups;
String[] in_groups_sorted;
class accDetails
{
int group_id;
String group_label;
Boolean _is_system;
}
This is just a part of how the class starts, and here is how the json reponse looks like:
{
"username":[
"mike"
],
"in_groups":[
{
"group_id":2,
"group_label":"All users",
"_is_system":true
},
{
"group_id":4372,
"group_label":"Privileged User",
"_is_system":false
},
{
"group_id":4979,
"group_label":"Supervisor",
"_is_system":false
}
]
}
The problem that i encounter now, is that i have no idea on how to split the in_groups array list and get into String[] in_groups_sorted the value of Group_label if the _is_system value is false.
Any help is highly appreciated.
Thank you,
Mike
After checking the responses, the cleanest and simplest was the one provided by Abbe:
public String[] groupSettings()
{
String[] levels = new String[] {};
if (remoteConfig != null && remoteConfig.in_groups != null){
for (accDetails ad: remoteConfig.in_groups)
{
if (!ad._is_system) {
levels = ArrayUtils.addAll(levels, ad.group_label); ;
}
}
}
return levels;
}
From your question, I suppose the JSON is already parsed and stored in the in_groups field of RemoteConfig class. And you just need to filter the information you need to populate the in_group_sorted field.
Add the following to the RemoteConfig class:
public initGroupSorted() {
// Temporary list, since we don't know the size once filtered
List<String> labels = new ArrayList<>();
for (accDetails ad : in_groups) {
if (ad._is_system) {
groups.add(ad.group_label);
}
}
in_group_sorted = labels.toArray(new String[labels.size()]);
}
if you don´t want to change the way you parse your JSON, you could always do this:
Let accDetails implement Comparable and then use Collections.sort passing in_groups.
if you really want the String[] you could always iterate over in_groups, add to in_groups_sorted and then using Arrays.sort
Mike, let me give you something that should get you going. From your question i got the feeling that your problem was on how to parse the JSON, so before you go write your own parser, consider the following piece of code that i just wrote:
public void createObjects(String rawJSON) {
try {
JSONObject object = new JSONObject(rawJSON);
JSONArray username = object.getJSONArray("username");
JSONArray inGroups = object.getJSONArray("in_groups");
RemoteConfig config = new RemoteConfig();
config.in_groups = new ArrayList<>();
config.username = username.getString(0);
for (int i = 0; i < inGroups.length(); i++) {
JSONObject group = inGroups.getJSONObject(i);
if (!group.getBoolean("_is_system")) {
accDetails details = new accDetails();
details.group_id = group.getInt("group_id");
details.group_label = group.getString("group_label");
details._is_system = false;
config.in_groups.add(details);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is a Java 8 Solution using Stream's filter,sorted, and map methods:
//ArrayList<accDetails> in_groups is already populated
Stream<accDetails> tempStream= in_groups.stream().filter(p -> p._is_system == false);
tempStream= tempStream.sorted((accDetails o1, accDetails o2) -> o1.group_label.compareTo(o2.group_label));
String[] in_groups_sorted = tempStream.map(s -> s.group_label).toArray(String[]::new);
Separated the calls for visibility, but they can be a one liner:
String[] in_groups_sorted = in_groups.stream().filter(p -> p._is_system == false).sorted((accDetails o1, accDetails o2) -> o1.group_label.compareTo(o2.group_label)).map(s -> s.group_label).toArray(String[]::new);

.equal in strings from json?

I'm trying some code where I want to compare strings i've grabbed from json to certain values. However the if statements never trigger. I have confirmed the values of the instances are set properly, and can be printed out.
//MAKING CLASSES
Collection collection = new ArrayList();
Event ev = new Event();
ev.name = "sven";
ev.source = "src10";
Event2 ev2 = new Event2();
ev2.name = "type";
ev2.data = "somedata";
collection.add(ev);
collection.add(ev2);
//MAKING A BUNCH OF CLASSES TO JSON
Gson gson = new Gson();
String json = gson.toJson(collection);
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();
//JSON TO JAVA
for (int i = 0; i < array.size(); i++) {
JsonObject nameObject = array.get(i).getAsJsonObject();
String nameString = nameObject.get("name").toString();
if (nameString.equals("sven")) {
System.out.println("this is sven");
Event event = gson.fromJson(array.get(i), Event.class);
}
else if (nameString.equals("type")) {
System.out.println("this is type");
Event2 event2 = gson.fromJson(array.get(i), Event2.class);
}
else{
System.out.println("nothing");
}
}
According Gson API your call to 'nameObject.get("name")' will return JsonElement. This means you should use 'getAsString()' method instead of 'toString()':
String nameString = nameObject.get("name").getAsString();
'toString()' method is designed (in general) for debugging purposes. And should be used very carefully in program logic.
You need to know that the implementation of toString() in JsonElement class is such that it will return the String inclusive of "".
To make it easier to understand look into the following code
JsonObject json = new JsonObject();
json.addProperty("hello", "tata");
System.out.println(json.get("hello").toString()); // Prints "tata"
System.out.println(json.get("hello").getAsString()); // Prints tata
so internally your code is comparing "sven" and sven which will return not equal

error message can't find symbol?

I am trying to create a double string. I thought that this is one way to assign values. I know there are better ways, but it was suggested by my teacher to do it this way. However when I put this in I get errors for each one stating:
can't find symbol cellPhoneNumbers
']' expected
Ultimately what I am trying to do is create a graph that looks something like this
Chile *******
Sweden *
Peru ***************
public class GraphNumbers
{
String[][] cellPhoneNumbers = new String[5][1];
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
}
Why am I receiving this message?
Some of the code must be placed in a method for example:
public class GraphNumbers
{
//changed the size of the array so you could do what you want
//you must have had a misscount when you originally made it
String[][] cellPhoneNumbers = new String[5][2];
//put in constructor or another appropriately named method
public GraphNumbers()
{
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
}
}
As per Java language syntax, you cannot put executable statements in class. Those should be put in either method/constructor/code blocks.
So you need to move these statements:
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
to appropriate place, maybe in a constructor.
Also your code is overflowing the array in stamens such as :
cellPhoneNumbers[0][1] = "21";
so you need the second dimension of array to be of size 2 and not 1. Change this
String[][] cellPhoneNumbers = new String[5][1];
to
String[][] cellPhoneNumbers = new String[5][2];

Get value from List<ListObject>

I am interestig in how to get value from Object from List<>.
Here is code example with Objects
#Override
public List<ListObject> initChildren() {
//Init the list
List<ListObject> mObjects = new ArrayList<ListObject>();
//Add an object to the list
StockObject s1 = new StockObject(this);
s1.code = "Системне програмування-1";
s1.num = "1.";
s1.value = "307/18";
s1.time = "8:30 - 10:05";
mObjects.add(s1);
StockObject s2 = new StockObject(this);
s2.code = "Комп'ютерна електроніка";
s2.num = "2.";
s2.value = "305/18";
s2.time = "10:25 - 11:00";
mObjects.add(s2);
StockObject s3 = new StockObject(this);
s3.code = "Психологія";
s3.num = "3.";
s3.value = "201/20";
s3.time = "11:20 - 13:55";
mObjects.add(s3);
StockObject s4 = new StockObject(this);
s4.code = "Проектування програмного забезпечення";
s4.num = "4.";
s4.value = "24";
s4.time = "14:15 - 16:50";
mObjects.add(s4);
return mObjects;
}
You can use get() method like follows
mObjects.get(index)
where index is the zero based index of your List, just like an array.
To directly access object, you do for example,
mObjects.get(index).code
you use like below
List<ListObject> mObjects = new ArrayList<ListObject>();
.......................your program...........
//access using enhanced for loop
for(ListObject myObj : mObjects){
System.out.println(myObj.code);
System.out.println(myObj.num);
System.out.println(myObj.value);
}
//access using index
int index=0;
System.out.println(mObjects.get(index).code);
You can iterate over the collection and type cast to the data type you know its in there.
List<ListObject> listOfObjects = initChildren();
for (Iterator iterator = listOfObjects.iterator(); iterator.hasNext();) {
StockObject so = (StockObject) iterator.next();
// do whatever you want with your StockObject (so)
System.out.println("Code:" + so.code);
}
You can use for each syntax as well like following
List<ListObject> listOfObjects = initChildren();
for (ListObject listObject : listOfObjects) {
StockObject so = (StockObject) listObject;
// do whatever you want with your StockObject (so)
System.out.println("Code:" + so.code);
}

Categories