I have the below pojo which consists of the below members so below is the pojo with few members in it
public class TnvoicetNotify {
private List<TvNotifyContact> toMap = new ArrayList<TvNotifyContact>();
private List<TvNotifyContact> ccMap = new ArrayList<TvNotifyContact>();
}
now in some other class i am getting the object of above class TnvoicetNotify in a method signature as parameter as shown below .. So i want to write the code of extraction from list and storing them in string array within this method itself
public void InvPostPayNotification(TnvoicetNotify TnvoicetNotify)
{
String[] mailTo = it should contain all the contents of list named toMap
String[] mailCC = it should contain all the contents of list named ccMap
}
now in the above class i need to extract the toMap which is of type list in the above pojo named TnvoicetNotify and i want to store each item if arraylist in a string array as shown in below fashion
for example first item in list is A1 and second is A2 and third is A3
so it should be stored in string array as
String[] mailTo = {"A1","A2","A3"};
similarly i want to achieve the same for cc section also as in above pojo it is in list i want to store in the below fashion
String[] mailCc = {"C1","C2","C3"};
so pls advise how to achieve this within InvPostPayNotification method
Pseudo code, because I don't know details for TnvoicetNotify:
public void invPostPayNotification(final TnvoicetNotify tnvoicetNotify)
{
final List<String> mailToList = new ArrayList<>();
for (final TvNotifyContact tv : tnvoicetNotify.getToMap()) { // To replace: getToMap()
mailToList.add(tv.getEmail()); // To replace: getEmail()
}
final String[] mailTo = mailToList.toArray(new String[mailToList.size()])
// same for mailCc then use both arrays
}
If you are using Java 8, you could simply use a one liner :
String[] mailCC = ccMap.stream().map(TvNotifyContact::getEmail).toArray(String[]::new);
Related
I am running into problem with a code for a text-based game. My class Locations is meant to load parameters from a "config" text file to create objects.
My current approach is:
I have created a public class with a constructor that will take the parameters of the object (location). It assigns them as this.xxx to private variables.
I have also created a public static class that parses the file, and once it has the necessary amount of parameters to create an object, it creates one by passing them to the constructor. Next, it adds that object to an ArrayList locations_list. Once all location objects were generated, the class returns the ArrayList locations_list
My static class parses the text file OK. However, when I run a test which iterates through locations_list and calls the getters for each element, the ArrayList parameters of objects are not individualized. All of the ArrayList elements return the same locations_characters.
The location_characters of all objects will have the same content, which is a list containing "characters" of all locations.
For example, if location 1 has characters 2 and 3 and location 2 has 6 and 7, my location_characters will print [2,3,6,7].
If I put a location_characters.clear(); after adding to location_list, the location_characters becomes empty for all objects.
Sample code snippets:
Public class with a constructor:
public class Locations {
private final int location_id;
private final String location_name;
private final String location_description;
private ArrayList <Integer> location_characters;
private ArrayList <Integer> location_items;
private final ArrayList <Integer> location_enter_from;
private final ArrayList <Integer> location_exit_to;
private String location_stage_name;
private final int location_stages;
private final ArrayList <String> location_stage_descriptions;
public Locations(int location_id,
String location_name,
String location_description,
ArrayList <Integer> location_characters,
ArrayList <Integer> location_items,
ArrayList <Integer> location_enter_from,
ArrayList <Integer> location_exit_to,
String location_stage_name,
int location_stages,
ArrayList <String> location_stage_descriptions) {
this.location_id = location_id;
this.location_name = location_name;
this.location_description = location_description;
this.location_characters = location_characters;
this.location_items = location_items;
this.location_enter_from = location_enter_from;
this.location_exit_to = location_exit_to;
this.location_stages = location_stages;
this.location_stage_descriptions = location_stage_descriptions;
}
... below are getters/setters....
Public static class for the loader:
public static ArrayList <Locations> load_locations() {
//These are used for parsing the text file
String line;
ArrayList <String> lines = new ArrayList<>();
//These are used to initialize local variables
int location_id = 0;
String location_name = null;
String location_description = null;
ArrayList<Integer> location_characters = new ArrayList<>();
ArrayList<Integer> location_items = new ArrayList<>();
ArrayList<Integer> location_enter_from = new ArrayList<>();
ArrayList<Integer> location_exit_to = new ArrayList<>();
String location_stage_name = null;
int location_stages = 0;
ArrayList<String> location_stage_descriptions = new ArrayList<>();
//This is used to initialize ArrayList of objects
ArrayList <Locations> location_list = new ArrayList<>();
//here goes the code for parsing the text files....
//below is a sample portion that loads i.e 2,3,4 split into ints,
//into the ArrayList location_characters....
case "location_characters":
String[] characters = values[1].split(",");
for (String character : characters) {
location_characters.add(Integer.parseInt(character));
}
i++;
break;
//continued...
//below I am passing the parameters into constructor,
//then adding the object to ArrayList location_list
}
Locations location = new Locations(location_id,
location_name,
location_description,
location_characters,
location_items,
location_enter_from,
location_exit_to,
location_stage_name,
location_stages,
location_stage_descriptions);
location_list.add(location);
i = 0;
}
}
reader.close();
}
catch (IOException e){
System.out.println("Problem reading file.");
}
return location_list;
}
I will appreciate insight and pointers to solution
Your code is incomplete, and the problem is in the code you're not showing: You're passing the same lists to all constructor calls, so all Locations objects are using the same lists for their fields.
This can be fixed by initializing Locations fields at their declarations, eg:
private List<Integer> location_characters = new ArrayList<>();
// repeat this pattern for all List fields
and not passing them lists through the constructor.
If you need to add to the list:
locationsInstance.getlocation_characters().add(foo);
I have a class Tag in java
public class Tag {
private int excerptID;
private String description;
}
and I am extracting descriptions from a list of Tag objects rawTags to a set (I need to remove duplicate values):
Set<String> tags = rawTags.stream().map(Tag::getDescription).collect(Collectors.toSet());
but I also want to have the resulting set (or list of unique descriptions) alphabetically ordered. Is there a way how to use TreeSet directly with Collectors or what would be the easiest way how to extract, remove duplicates and order alphabetically?
public static void main(String[] args) {
Tag tag1 = new Tag(1,"9a");
Tag tag2 = new Tag(2,"32");
Tag tag3 = new Tag(3,"4c");
Tag tag4 = new Tag(4,"1d");
List<Tag> rawTags = new ArrayList<>();
rawTags.add(tag1);rawTags.add(tag2);rawTags.add(tag3);rawTags.add(tag4);
Set<String> tags = rawTags.stream().map(Tag::getDescription).collect(Collectors.toCollection(TreeSet::new));
System.out.print(tags);
}
You can use Collectors.toCollection and pass method reference to TreeSet constructor:
Set<String> tags = rawTags.stream() //or you can assign to TreeSet directly
.map(Tag::getDescription)
.collect(Collectors.toCollection(TreeSet::new));
and in case you wanted to pass custom comparator :
.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
I am creating a class to sort some data.
class data{
public String text;
public String day;
public String direction;
}
dados vetor[]={};
Now I have to have to change a varible and I am doing it this way:
vetor[0].text="dumb text";
But I am gettting this error:
Attempt to write to field java.lang.String on a null object reference
Unless you reassigned the array to something else, this is your problem.
dados vetor[]={};
You create an empty array - there is no data object at vetor[0] for you to set the text of. If you know the number of elements you'll have when you declare the array, you can use the following to create an array to hold all of them.
dados[] vetor = new dados[10];
To actually create an element in that array and set its text, you need to create a new object.
vetor[0] = new data();
vetor[0].text = "Some text";
Alternatively, create and set the values for the data object before adding it to the array:
data myData = new data();
myData.text = "Some text";
vetor[0] = myData;
You probably did something like :
vetor[0] = someInstanceOfData.text; // Store value in array
However now vetor[0] contains the value of the text field (i.e. a String).
You can not access the text field later by doing vetor[0]. This refers to the String that is stored in that array. So if later the value of the text field changes, the vector will still contain the old.
Hence vetor[0].text="dumb text"; is not assigning the text field of some instance of the data class, but instead is trying to assign a new value to the String that results from vetor[0].
EDIT : If you want to change the value of the text field :
Data test = new Data(); // Make an instance of the Data class
test.text = "A String"; // Assign a value
If you want to make an array (of strings? or data objects?)
Data[] arr = {new Data(), new Data(), new Data()}; // Using the litteral
String[] arrOfStrings = {test.text, test.day, test.direction};
If you want to access/assign e.g. text from a data object storen in arr
arr[0].text = "Another String";
arrOfStrings[0].text = ...; // Not possible because it is storing strings not Data objects!
If you don't know the length before hand, you can not use an array (as they are of fixed length). Instead you could use List's which are of variable length.
List<Integer> test = new ArrayList<Integer>();
test.add(1); // Add elements
test.size(); // How long is my array at the moment?
test.get(0); // Access first element (index 0) --> 1
Applying this to your code :
dados testObject = new dados(); // create a "dados" object
List<dados> testList = new ArrayList<dados>();
testList.add(testObject);
testList.get(0); // Get object on index 0 (hence the first), hence "testObject"
To sort the ArrayList of dados objects you should implement a custom comparator to sort the objects like you want
public class OwnComparator implements Comparator<Dados> {
#Override
public int compare(Dados obj1, Dados obj2) {
return obj1.text.compareTo(obj2.text); // Sort based on "text" field
}
}
The actual sorting
Collections.sort(testList, new OwnComparator());
I am assuming your class name is "dados" and not "data".
Your array does not have any elements, hence the error.
Initialize your array to a certain number of elements and then assign the text property.
dados[] vetor = new dados[10];
vetor[0] = new dados();
vetor [0].text = "xx";
dados[] vetor2 = {new dados(), new dados()}; // initialize to 2 elements
vetor2[0].text = "xx";
So I have a class called Test:
public class Test{
protected String name = "boy";
protected String mainAttack = "one";
protected String secAttack = "two";
protected String mainType"three";
protected String typeSpeak = "no spoken word in super class";
//Somehow put all the class variables in an Array of some sort
String[] allStrings = ??(all class' strings);
//(and if you feel challenged, put in ArrayList without type declared.
//So I could put in, not only Strings, but also ints etc.)
public void Tester(){
//Somehow loop through array(list) and print values (for-loop?)
}
}
As you can see, I want to put all the class variables in an Array or ArrayList (or something similar) automatically.
And next I want to be able to loop through the array and print/get the values.
Preferably using an enhanced-for loop.
As other said, don't do this. But this is how:
Class<?> cl = this.getClass();
List<Object> allObjects = new ArrayList<Object>();
for (java.lang.reflect.Field f: cl.getDeclaredFields())
{
f.setAccessible(true);
try
{
Object o = f.get(this);
allObjects.add(o);
}
catch (Exception e)
{
...
}
}
for (Object o: allObjects)
System.out.println(o);
If you really really need do this you need to use Reflection.
However a much better approach would be to store the values in a Map (probably a HashMap) and then you can query/set/etc them from that easily.
You can use Map or Hashmap to store variables and its values instead of Array or Arraylist
HashMap is an object that stores both “key/value” as a pairs. In this article, we show you how to create a HashMap instance and iterates the HashMap data.
Why not use a HashMap for the values and iterate through that?
Iterate through a HashMap
Do this.
String threeEleves = "sky";
String sevenDwarves = "stone";
String nineMortal = "die";
String oneRing[] = new String[] // <<< This
{
threeElves,
sevenDwarves,
nineMortal
}
or do this
// in some class.
public void process(final String... varArgs)
{
for (String current : varArgs)
{
}
}
String one = "noodles";
String two = "get";
String three = "in";
String four = "my";
String five = "belly";
process (one, two, three, four, five);
I am trying to create a java function where it takes 2 parameter. One is comma delimited list of string that represent what will be called for radio button. Second is comma delimited list of string that represents the variable respected to 1st parameter.
For example, If I write f1("apple,banana", "a,b"), I wanted to make JRadioButton with apple and banana along with a and b being their variable.
Is this possible?
I tried to use split(",") but I did not get too far...
Thanks in advance!
EDIT: I came up with following but still now luck..
static void f5(String question, String rbLabel, String rbVar, String help)
{
JOptionPane.showInputDialog(question);
ArrayList<String> rbLabelAL = new ArrayList<String>();
ArrayList<String> rbVarAL = new ArrayList<String>();
String[] token;
String[] token2;
token = rbLabel.split(",");
token2 = rbVar.split(",");
if(token.length == token2.length)
{
for(int i=0;i<token.length;i++)
{
rbLabelAL.add(token[i]);
rbVarAL.add(token2[i]);
}
}
JRadioButton(rbLabelAL(0));
}
Following up on my comment....if you wanted to do something like this, I would suggest creating an arraylist.
Something like.... ArrayList<String> options = new ArrayList<String>();
Add in your options....options.add("apple");
Then pass the arraylist into your method and create the radio buttons as such...JRadioButton(options(i));
Of course you would have to iterate through the list to create all buttons.