Transformation of an Array to another Array - java

I need to transform an array of one type to an array of another type.
More specifically, I need to pull just a couple fields from each object in the starting array to create the resulting array, which will contain only those 2 fields, though named differently.
For example, let's say I have an array of Thing objects:
public class Thing {
private String id;
private String description;
... // other fields
}
I need to create from that an array of Item objects:
public class Item {
private String code;
private String data;
...
}
... where the id from each Thing becomes code in each Item; and description becomes data.
I've seen examples of using the Stream api to transform an array of objects to an array of Strings. But it's unclear to me thus far how to transform an object to another object.

Try this.
record Thing(String id, String description) {}
record Item(String coded, String data) {}
public static void main(String[] args) {
Thing[] array = {new Thing("1", "one"), new Thing("2", "two")};
Item[] transformed = Arrays.stream(array)
.map(thing -> new Item(thing.id(), thing.description()))
.toArray(Item[]::new);
System.out.println(Arrays.toString(transformed));
}
output:
[Item[coded=1, data=one], Item[coded=2, data=two]]

Related

Convert POJO List to CSV comma delimited String

I have a List of ProcessedClass (POJO I have created) that I would like to generate to a string of comma-delimited values. So all items in the list output to a single, comma-delimited list.
My plan is to: pass the list into a method, iterate through the list and append commas and finally remove the last comma and return the resulting string. The object being processed will have some nested POJO's with multiple different variable types (string, int, boolean, other POJO's, LocalDate etc..). I have added an example of the structure below.
My question is what is the best way to go about constructing this? Thank you in advance.
Example structure being processed:
//List<ProcessedClass> will be passed into the iternation method
public class ProcessedClass {
private Other other;
private Info info;
}
public class Other {
private String stringMessage;
private boolean booleanValue;
...
}
public class Info {
//Another defined POJO
private User user;
private LocalDate date;
private String name;
...
}
You can use StringJoiner with , delimiter.
StringJoiner stringJoiner = new StringJoiner(",");
processedClasses.forEach(a -> stringJoiner.add(a.toString()));
System.out.println(stringJoiner);
Of course, you have to implement the toString method in all defined classes.

Easy way to get to values from JSONArray

I recently started working with JSON in Java. We have been setting and getting our values as follows from this JSONArray:
[{"productId":"1"},{"productName":"hammer"}]
JSONObject jo = ja.getJSONObject(0);
We could easily get the values by calling jo.getString("productId"); which would return the 1.
The problem is that sometimes we get different types of JSON objects. They look like this:
[{"name":"productId", "value":"1"},{"name":"productName", "value":"hammer"}]
Is there a way to easily eliminate those predicate name/value and just group the actual name and value together (as in the first example)?
The short answer is no.
The longer answer is that you're not working with JSON, you're working with someone's misunderstanding of JSON.
Both of your examples look a bit like JSON, but they're both bogus.
[] is an array.
{} is an object.
Your first string [{"productId":"1"},{"productName":"hammer"}]
is an array of two objects, where each object has one property.
It's confusing to put dissimilar objects into an array together, but that's going on in both of your examples.
The second example [{"name":"productId", "value":"1"},{"name":"productName", "value":"hammer"}] shows an array of two objects, but again, the objects are dissimilar.
I think what they're going for is more like [{"productId":"1","productName":"hammer"}], so I guess the long answer to your question is that you need to go to whomever is providing this "JSON" and tell them to fix it.
To give you a clearer idea of the correspondence between objects (in Java and otherwise) and JSON, check out the Java program below:
public class Product {
String productName;
String productId;
public Product(String productId,String productName){
this.productName = productName;
this.productId = productId;
}
public String toString(){return toJSONString();}
public String toJSONString(){
return "{\"productId\":\""+productId+",\"productName:\""+productName+"\"}";
}
public static String arrayToJSONString(Product[] arry){
StringBuilder sb = new StringBuilder();
sb.append("["+arry[0]);
for (int n =1;n<arry.length;n++){
sb.append(","+arry[n]);
}
sb.append("]");
return sb.toString();
}
public static void main(String [] args){
Product p1 = new Product("1","hammer");
Product[] arry = {p1};
Product[] arry2 ={p1,new Product("2","shovel"), new Product("3","manure")};
System.out.println("One object");
System.out.println(" "+p1);
System.out.println("An array containing one object");
System.out.println(" "+Product.arrayToJSONString(arry));
System.out.println("An array containing three objects");
System.out.println(" "+Product.arrayToJSONString(arry2));
}
}
Here's the output showing the proper JSON representation:
One object
{"productId":"1,"productName:"hammer"}
An array containing one object
[{"productId":"1,"productName:"hammer"}]
An array containing three objects
[{"productId":"1,"productName:"hammer"},{"productId":"2,"productName:"shovel"},{"productId":"3,"productName:"manure"}]
(Newlines are an artifact of the HTML, not JSON)

Adding a string parameter to an object

This is what I need to do. I'm not really sure how though.
addGrade() method: Accepts a String parameter representing a new grade (including category prefix) to add to the GradeBook object; and returns true if added or false if not added (e.g., if category was not in the category array).
private String[] categories;
public Gradebook(String[] categoriesIn) {
categories = categoriesIn;
}
public boolean addGrade(String newGrade) {
categories[] = new Gradebook(newGrade);
}
I tried that above for starters but that's not correct
you cannot instantiate Gradebook Class in to variable categories, because variable categories is Array of String
try to instance new array, then assign to variable categories

initializing an object in an array

I've been playing around with arrays for some time and this problem has been troubling me.
I created a user defined object and declared it in an array like this: `Property regesteredAssets[] = new Property[200];
And here's my constructor: `
public Property(String newPropertyName,String newPropertyAddress,String newPropertyType, String newPropertyDescription)
{
propertyName[arraySequence] = newPropertyName;
propertyFullAddress[arraySequence] = newPropertyAddress;
propertyType[arraySequence] = newPropertyType;
propertyDescription[arraySequence] = newPropertyDescription;
arraySequence++;
}
I want to initialize each array regesteredAsssets[] according to my desire. How can I do it?
Do I have to use arrays in my attributes in the Property class too?
You do not need your attributes to be arrays, unless a particular asset has multiple of something. In this case, I don't think it does. You can greatly simplify your code as follows:
public class Property {
private String name, address, type, description;
public Property(String name, String address, String type, String description) {
this.name = name;
this.address = address;
this.type = type;
this.description = description;
}
public static void main(String[] args) {
Property[] registeredAssets = new Property[200];
registeredAssets[0] = new Property("Joe Bloggs", "555 Fake St.", "IMPORTANT", "Lorem Ipsum Dolor");
// etc.
}
}
If you have an array of type Property, you can set each of the elements up using the following code:
regesteredAssets[0] = new Property( enterYourParametersHere );
I assume the fields in your Property constructor are single fields, and therefore you do not need to set them using the array notation field[index] = value, and indeed, if the Property class is of the consistency I think it is, then this will produce a compilation error.
If you wanted to set up multiple entries in your array, you could perform the initialisation step inside a loop, providing a loop index to the index of the array as below:
for( int i = 0; i < 10; i++ )
{
regesteredAssets[i] = new Property( enterYourParametersHere );
}
I hope this helps...

Creating an array of Sets in Java

I'm new to Java so I'm probably doing something wrong here,
I want to create an array of Sets and I get an error (from Eclipse).
I have a class:
public class Recipient
{
String name;
String phoneNumber;
public Recipient(String nameToSet, String phoneNumberToSet)
{
name = nameToSet;
phoneNumber = phoneNumberToSet;
}
void setName(String nameToSet)
{
name = nameToSet;
}
void setPhoneNumber(String phoneNumberToSet)
{
phoneNumber = phoneNumberToSet;
}
String getName()
{
return name;
}
String getPhoneNumber()
{
return phoneNumber;
}
}
and I'm trying to create an array:
Set<Recipient>[] groupMembers = new TreeSet<Recipient>[100];
The error I get is "Cannot create a generic array of TreeSet"
What is wrong ?
From http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html:
you cannot instantiate an array of a generic type (new List<String>[3] is illegal), unless the type argument is an unbounded wildcard (new List<?>[3] is legal).
Rather than using an array, you can use an ArrayList:
List<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();
The code above creates an empty ArrayList of Set<Recipient> objects. You would still have to instantiate every Set<Recipient> object that you put into the ArrayList.
Arrays don't support Generics. Use an ArrayList:
ArrayList<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();
You might want to consider using Guava's Multimap where the key is the index. This will handle creating the Sets for each index as you need them.
SetMultimap
SetMultimap<Integer, Recipient> groupMembers;

Categories

Resources