I have a Class Foo that has a Constructor that sets name and id.
In another Class I have a List<String> of messages where I can extract the name and id.
I'm able to successfully set the Constructor by looping through the list using regular foreach loop. How do I achieve this using Stream Java 8 or Lambda or Method References
public class ConstructorTest {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
List<String> userList = new ArrayList<String>();
userList.add("username1_id1");
userList.add("username2_id2");
//I want to replace the below foreach loop with stream/lambda/methodreferences
for (String user : userList) {
Foo foo = new Foo(getName(user), getId(user));
fooList.add(foo);
}
}
private static String getName(String user) {
return user.split("_")[0];
}
private static String getId(String user) {
return user.split("_")[1];
}
}
Foo Class:
public class Foo {
public Foo(String name, String id) {
this.name = name;
this.id = id;
}
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
How about this?
userList.stream().map(user -> new Foo(getName(user), getId(user)).forEach(userList::add)
Or this
userList.forEach(user -> userList.add(new Foo(getName(user), getId(user))))
Related
This is my object :
public class ObjectsInGroupRealm extends RealmObject {
#PrimaryKey
private Long id;
private String name;
private String groupName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
And when I create a new object I want to check if object is exist this same name and this same groupName . A object name could be in few groups. This is my code how I save a objects :
public static void saveObjectsInGroup(ArrayList<String> objects, String groupName , Realm realm){
for(String object : objects){
ObjectsInGroupRealm objectsInGroupRealm = new ObjectsInGroupRealm();
Long key;
try {
key = (Long) realm.where(ObjectsInGroupRealm.class).max("id") + 1;
} catch (NullPointerException ex) {
key = 0L; // when there is no object in the database yet
}
objectsInGroupRealm.setId(key);
objectsInGroupRealm.setName(object);
objectsInGroupRealm.setGroupName(groupName);
realm.beginTransaction();
realm.copyToRealm(objectsInGroupRealm);
realm.commitTransaction();
}
}
So the easiest way is doing a query and checking if the returned Object is null:
ObjectsInGroupRealm object = realm.where(ObjectsInGroupRealm.class)
.equalTo("name", name)
.equalTo("groupName", groupName)
.findFirst();
if(object == null){
//add new object
} else {
//handle object already existing
}
I have the following advice code:
#Around("annotatedMethod()")
public Object aroundGetPanel(ProceedingJoinPoint joinPoint) throws Throwable
{
Object result = joinPoint.proceed();
return result;
}
And the method who executes the above method is:
public Person getPerson(String id){
return new Person(1,"Maialen");
}
public class Person {
private Integer id = null;
private String name = null;
public Person(Integer id,String name){
this.setId(id);
this.setName(name);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return nombre;
}
public void setName(String name) {
this.name = name;
}
}
How can I get the params of object result (Person)?
Using reflection? Using annotations?
I discovered how to do it via reflection:
Class<?> clazz = result.getClass();
Field field = org.springframework.util.ReflectionUtils.findField(clazz, "name");
org.springframework.util.ReflectionUtils.makeAccessible(field);
String name=field.get(result).toString();
But I prefer do it by annotations. Is there a mode?
I have 3 classes - Patient, AllergyList and Allergy. Both Patient and Allergy are #Entity and AllergyList simply has a variable with a list of Allergiest.
#Entity
public class Allergy {
private String id;
private String name;
public Allergy(String i, String n) {
id=i;
name=n;
}
#Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
}
The Allergy class MUST have an id, and is referenced by other class in my program.
public class AllergyList {
private List<Allergy> allergies = new ArrayList<Allergy>();
public List<Allergy> getAllergies() {
return allergies;
}
public void setAllergies(List<Allergy> a) {
this.allergies = a;
}
}
I need to have this class, because I have inherited the program, and cannot change the existing codebase.
#Entity
public class Patient {
private String id;
private AllergyList allergyList = new AllergyList();
public Patient() {}
#Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public AllergyList getAllergyList() {
return allergyList;
}
public void setAllergyList(AllergyList allergyList) {
this.allergyList = allergyList;
}
}
And the main...
public static void main(String[] args) {
Patient patient = new Patient();
patient.setId("100001");
List<Allergy> allergies = new ArrayList<Allergy>();
allergies.add(new Allergy("1","Dust"));
allergies.add(new Allergy("3","Apple"));
allergies.add(new Allergy("4","Bee"));
patient.allergyList.setAllergies(allergies);
.
.
session.save(patient);
.
.
}
So the above three classes are what I'm given. I need to create allergy_list table that contains the following:
allergy_list
patient_id
allergy_id
I know I can create a List inside the Patient class, but the way the program is written I need to access the Allergy through the AllergyList class. How can I annotate to make this happen? Is it even possible?
it's been a while since I've done some java coding.
I need to build an application for a business which requires automation (part of a workshop), which is however irrelevant to my question...
I'm stuck on the line : customerList.add(customer); //(part of the addCustomer method in the WCIA class)
Also it's the first time I'm told to "Assign return value to new Variable" as part of an error, so not too sure what that means.
Code: Main
import java.util.ArrayList;
public class WCIA {
private final ArrayList customerList = null;
public static void main(String[] args) {
short s =002;
Customer arno = new Customer();
arno.setName("Arno");
arno.setId(s);
arno.setEmail("arnomeye#gmail.com");
arno.setAddress("Somewhere");
arno.setPhoneNum("0727855201");
System.out.printf("%s",arno.getEmail());
WCIA wcia = new WCIA();
wcia.addCustomer(arno);
wcia.displayCustomers();
}
public void addCustomer (Customer customer)
{
customerList.add(customer); // <---Problem over here
}
public void displayCustomers()
{
for(int x=0;x<customerList.size();x++)
{
Customer cus = (Customer) customerList.get(x);
cus.DisplayCustomer();
}
}
}
Code: Customer class:
public class Customer {
private short id;
private String name;
private String email;
private String phoneNum;
private String address;
public Customer()
{
System.out.println("Class initiated");
}
public void DisplayCustomer()
{
System.out.append("Name : "+ name+"\n");
System.out.append("ID : "+ id+"\n");
System.out.append("Email : "+ email+"\n");
System.out.append("Phone Number : "+ phoneNum+"\n");
System.out.append("address : "+ address+"\n");
}
public void setId(short id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public void setAddress(String address) {
this.address = address;
}
public short getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPhoneNum() {
return phoneNum;
}
public String getAddress() {
return address;
}
}
You need to instantiate your ArrayList before you can assign elements to it. You're probably getting a NullPointerException, is my guess.
Change this line:
private final ArrayList customerList = null;
to
private final ArrayList customerList = new ArrayList();
Should solve at least this problem. I did not read the rest of your code so I'm not sure if other problems exist.
customerList is null and never initialized. Create an object of type ArrayList and assign it to that variable before you try to add to it.
You should declare the List with an explicit definition of the type of its elements (parametrized list):
private final List<Customer> customerList;
This way you can get rid of casting to Customer in:
Customer cus = customerList.get(x);
Finally, as good practice, initialize it in the constructor:
public WCIA()
{
customerList = new ArrayList<>();
}
Normally if we want to initialize a generic non-primitive ArrayList we do this
ArrayList<?> arrayList = new ArrayList<MyClass.class>();
But I want to do something similar to this no matter which class object I pass, i.e
private void getModel(Class responseType){
//Something similar, because this does not work..
ArrayList<?> arrayList = new ArrayList<responseType>();
}
Any Help would be greatly appreciated.
Try something like this
private <T> void setModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
}
If you want to get the list back then
private <T> ArrayList<T> getModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
EDIT
A FULL EXAMPLE SHOWING HOW TO USE GENERIC TYPE FOR ARRAYLIST
Tester class with main method and the generic Method
public class Tester {
private <T> ArrayList<T> getModels(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = (ArrayList<Data>) t.getModels(Data.class);
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = (ArrayList<Magic>) t.getModels(Magic.class);
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
Another possibility to use the same things without parameter since we don't use it inside the method
public class Tester {
private <T> ArrayList<T> getModel() {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = t.getModel();
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = t.getModel();
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
Model class (Data)
public class Data {
private Integer id;
private String name;
public Data() {
}
public Data(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
Model class (Magic)
public class Magic {
private Integer id;
private String name;
public Magic() {
}
public Magic(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
This works:
private void getModel(){
ArrayList<?> arrayList = new ArrayList<Object>();
}
I mean, it is unclear what you are trying to do. Generics is purely compile-timem, to perform compile-time type checking. Therefore, if the type parameter is not known at compile time, it would be useless.
Try using following
public <T> List<T> getList(Class<T> requiredType) {
return new ArrayList<T>();
}
public void useList() {
List<Integer> ints = getList(Integer.class);
List<String> lists = getList(String.class);
}