I am writing a function that will create an object with data. So far I get objects with data but individually not as a collection. I would like to return an object with all designated data as one Student object, not just one input for every object. I tried to add objList.add(obj) out of the for loop too and outputs all null.
Here is the code
class Student{
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
public static List<Object> createObject(Student st, List<Map<String, String>> csvStudentData) {
List<Object> objList = new ArrayList<>();
Object obj = null;
for(Map<String, String> studentData: csvStudentData) {
for (Map.Entry<String, String> entry = studentData.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
obj = insertObjectData(st.getClass(), key, value);
objList.add(obj);
}
}
return objList;
}
You modify the method's body by the following:
public static List<Object> createObject(Student st, List<Map<String, String>> csvStudentData) {
List<Student> objList = new ArrayList<>();
for(Map<String, String> studentData: csvStudentData) {
Student student = new Student();
for (Map.Entry<String, String> entry = studentData.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
Field field = Student.class.getDeclaredField(key);
student.set(field, value);
}
objList.add(student);
}
return objList;
}
you also add a default constructor in the class Student
You can do it in java-8 stream
List<Object> objList = csvStudentData.stream()
.flatMap(map->map.entrySet()
.stream()
.map(entry->insertObjectData(st.getClass(), entry.getKey(), entry.getValue())))
.collect(Collectors.toList());
Related
This question already has answers here:
Java 8 lambdas group list into map
(2 answers)
Closed 3 years ago.
I have a class named People
public class People{
private String name;
private String email;
private String accountnum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAccountnum() {
return accountnum;
}
public void setAccountnum(String accountnum) {
this.accountnum= accountnum;
}
public People(String name, String email, String accountnum) {
this.name = name;
this.email = email;
this.accountnum= accountnum;
}
}
I have a ArrayList of objects that created from this class
People peop1 = new People("john", "john#gmail.com", "56hk");
People peop2 = new People("Rose", "rose#gmail.com", "5689hk");
People peop3 = new People("john", "john#gmail.com", "5676hk");
People peop4 = new People("Rose", "rose#gmail.com", "6799hk");
People peop5 = new People("Jack", "jack#gmail.com", "7009hk");
List<People> peoplelist = new ArrayList<People>();
peoplelist .add(peop1);
peoplelist.add(peop2 );
peoplelist .add(peop3 );
What i want to do is to retrieve the email and its accountnums.
like this
john#gmail.com = {56hk,5676hk};
rose#gmail.com = {5689hk,6799hk};
jack#gmail.com = {7009hk}
I know i can loop through and return a map or use java streams and collection framework. But I don't know how to do it.
I tried to find similar solution but couldn't find any sorry if this is already asked.
Are there any way to do that?
The collect all different accountnums of each person, you could use a HashSet. It would automatically eliminate duplicate values.
To collect the data of all persons, you could use a HashMap with email address as the key and the set of accountnums as the value.
Example:
import java.util.*;
class Main
{
public static void main(String[] args)
{
// Create example input data
List<People> peopleList = new ArrayList<People>();
peopleList.add(new People("john", "john#gmail.com", "56hk"));
peopleList.add(new People("Rose", "rose#gmail.com", "5689hk"));
peopleList.add(new People("john", "john#gmail.com", "5676hk"));
peopleList.add(new People("Rose", "rose#gmail.com", "6799hk"));
peopleList.add(new People("Jack", "jack#gmail.com", "7009hk"));
// To collect the result. key=email, value=set of accountnum
Map<String, Set<String>> map = new HashMap<>();
// Iterate over the input
for (People person : peopleList)
{
// Get the existing data for the email address of this person
Set<String> acountNumbers = map.get(person.getEmail());
// If this is the first record for the email...
if (acountNumbers == null)
{
// Create a new HashSet to collect the account numbers for this email
acountNumbers = new HashSet<String>();
acountNumbers.add(person.getAccountnum());
map.put(person.getEmail(), acountNumbers);
}
else
{
// Add the accountnum to the existing set of account numbers
acountNumbers.add(person.getAccountnum());
}
}
// Output the result
for (Map.Entry<String, Set<String>> entry : map.entrySet())
{
String email = entry.getKey();
Set<String> acountNumbers = entry.getValue();
System.out.println(email + " = " + acountNumbers);
}
}
}
Outputs:
rose#gmail.com = [5689hk, 6799hk]
john#gmail.com = [5676hk, 56hk]
jack#gmail.com = [7009hk]
I have hashmap string object below. How to get value name from object SubSource.value index 0? I just found function for get first object, for example I just get value from test with hashMapValue.get("test"). How to get value object inside the object? should I convert to json and I get the value? Thanks.
{
"test" : {
"type" : "",
"value" : ""
},
"Attachment" : {
"type" : "",
"value" : ""
},
"SubSource" : {
"type" : "string",
"value" : [ {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "bobby"
}, {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "2sadasd"
}, {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "ggfgf"
} ]
}
}
My code:
Map<String, Object> departmentPHSSuportEmail = new HashMap<String, Object>();
Map<String, Object> subSourceMap = null;
List<Map<String , Object>> myMap = new ArrayList<Map<String,Object>>();
Map<String, Object> attachment = new HashMap<String, Object>();
attachment.put("type", "");
attachment.put("value", "");
departmentPHSSuportEmail.put("Attachment", attachment);
Map<String, Object> subSource = new HashMap<String, Object>();
subSource.put("type", "string");
subSource.put("value", myMap);
departmentPHSSuportEmail.put("SubSource", subSource);
// create a fresh map
Map<String,Object> subSourceMap1 = new HashMap<>();
subSourceMap1.put("name", "bobby");
subSourceMap1.put("address", "xxx.xxxx#xxx.co.id");
// create a fresh map
Map<String,Object> subSourceMap2 = new HashMap<>();
subSourceMap2.put("name", "2sadasd");
subSourceMap2.put("address", "xxx.xxxx#xxx.co.id");
// create a fresh map
Map<String,Object> subSourceMap3 = new HashMap<>();
subSourceMap3.put("name", "ggfgf");
subSourceMap3.put("address", "xxx.xxxx#xxx.co.id");
myMap.add(subSourceMap1);
myMap.add(subSourceMap2);
myMap.add(subSourceMap3);
Map<String, Object> attachments = new HashMap<String, Object>();
attachments.put("type", "");
attachments.put("value", "dasda");
departmentPHSSuportEmail.put("test", attachments);
Not sure what you are asking, but...
A) Cast the object you are getting from the map to the Object type you are trying to grab the values out of
String name = (String) subSourceMap1.get("name");
B) Add type parameters to your map
Map<String, String> subSourceMap1 = new HashMap<String, String>();
String name = subSourceMap1.get("name");
String address = subSourceMap1.get("address");
C) If you are wondering how to get those maps out of a list
Map<String, YourObject> subSourceMap1 = myMap.get(0); //This is index 0's of your map subsource
//You can grab index's from 'myMap' that are less than myMap.size();
This is a JSON string. Find a proper JSON deserializer library and include that in your project instead of coding all this HashMap stuff.. ;)
Ie this
jackson-2-convert-object-to-from-json
Map<String, Object> subSource2 = (Map<String, Object>)departmentPHSSuportEmail.get("SubSource");
List<Map<String , Object>> myMap2 = (List<Map<String , Object>>)subSource2.get("value");
Map<String,Object> subSourceMap3 = myMap2.get(0);
String value = (String)subSourceMap3.get("value");
There are many ways how to solve this, one of solutions can be like this:
make container for member data (address + name), if the addresses
should be unique, than can be used as a key in map
make container for attachment
make container for the whole data, because of data integrity
Please, notice, I have used hashmap for members, but arraylist for attachments, if you are expecting also unique values at attachments, than you can use also hashmap with key name, then you can use it for finding
So..
Member container
public class Member {
private String name;
private String address;
public Member(String name, String address) {
super();
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
Container for attachments
public class Attachment {
String name;
String value;
public Attachment(String name, String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Than container for complete data
public class DataContainer {
Map<String, Member> membersMap;
ArrayList<Attachment> attachments;
public DataContainer() {
this.membersMap = new HashMap<String, Member>();
this.attachments = new ArrayList<Attachment>();
}
public DataContainer(Map<String, Member> membersMap, ArrayList<Attachment> attachments) {
super();
this.membersMap = membersMap;
this.attachments = attachments;
}
public Map<String, Member> getMembersMap() {
return membersMap;
}
public void setMembersMap(Map<String, Member> membersMap) {
this.membersMap = membersMap;
}
public ArrayList<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<Attachment> attachments) {
this.attachments = attachments;
}
public void addAttachment(Attachment newItem) {
this.attachments.add(newItem);
}
public void addMember(Member newMember) {
this.membersMap.put(newMember.getAddress(), newMember);
}
public Member getMemberByAddress(String address) {
return this.membersMap.get(address);
}
}
Filling example
Map<String, Member> membersMap= new HashMap<String, Member>();
Member newMember = new Member("fooo Name", "fooo#whatever.foo");
membersMap.put(newMember.getAddress(), newMember);
Attachment newAtatchment = new Attachment("fooattach", "something");
ArrayList<Attachment> attachments = new ArrayList<>();
attachments.add(newAtatchment);
DataContainer data = new DataContainer(membersMap, attachments);
data.addMember(new Member("anotherMember", "fooo#foooo.foo"));
data.addAttachment(new Attachment("another attachmetn", "anotherAtt value"));
I know this question is kind of repetitive But still I can't get an answer.
I have 2 arraylists containing name and description respectively as
final ArrayList<String> arrayOne = new ArrayList<String>(); // containing names
final ArrayList<String> arraytwo = new ArrayList<String>(); // containing description
I need a view like
I have tried
arraytwo.add(arrayOne);
&
arrayThree.addAll(arrayOne);
arrayThree.addAll(arrayTwo);
But can't a desired arraylist.
Regards
POJO class
public class Model
{
String name;
String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
desc = desc;
}
}
For Storing to arraylist
ArrayList<Model> arrayModel = new ArrayList<Model>();
for(int i=0;i<arrayOne.size();i++)
{
Model model=new Model();
model.setName(arrayOne.get(i));
model.setDesc(arrayTwo.get(i));
arrayModel.add(model);
}
If you don't want to create POJO, try this:
List<String> nameList;
List<String> desList;
//for storing
Map<String, String> map = new HashMap<>();
for(int i=0;i<nameList.size();i++) {
map.put(nameList.get(i), desList.get(i));
}
//for retrieving
for(Map.Entry<String, String> m : map.entrySet())
String nameListItem = m.getKey();
String desListItem = m.getValue();
}
I would like to be able to test if a List contain an object with a given key-value
For example, I would like to do something like Iterables.contains(l2, "lname", "Jordan")); instead of having to create all other Map objects like below in l2
//List<String> l = Arrays.asList("Mickael", "Jordan", "His Airness");
//System.out.println(Iterables.contains(l, "Jordan"));
Map<String, String> p1 = new HashMap<String, String>();
p1.put("fname", "Mickael");
p1.put("lname", "Jordan");
p1.put("nname", "His Airness");
Map<String, String> p2 = new HashMap<String, String>();
p2.put("fname", "Paul");
p2.put("lname", "Pierce");
p2.put("nname", "The Truth");
List<Map<String, String>> l2 = Arrays.asList(p1, p2);
Map<String, String> p3 = new HashMap<String, String>();
p3.put("fname", "Mickael"); //
p3.put("lname", "Jordan");
p3.put("nname", "His Airness"); //
System.out.println(Iterables.contains(l2, p3));
I'd like to know if there's such guava's function, and not doing a loop on l2 and testing each elt.get("lname")
Edit
3 solutions answered: trying to see which one is more perfomant
System.out.println(Iterables.any(l2, withEntry("lname", "Jordan"))); //#axtavt
System.out.println(has("lname", "Jordan")); //#JB
System.out.println(Iterables.any(l2, new KeyValuePredicate("lname", "Jordan"))); //#JB
public static Boolean has(final String key, final String value) {
return Iterables.any(l2, new Predicate<Map<String, String>>() {
#Override
public boolean apply(Map<String, String> input) {
return input.get(key).equals(value);
}
});
}
public static Predicate<Map<String, String>> withEntry(final String key, final String value) {
return new Predicate<Map<String, String>>() {
public boolean apply(Map<String, String> input) {
return value.equals(input.get(key));
}
};
}
class KeyValuePredicate implements Predicate<Map<String, String>>{
private String key;
private String value;
public KeyValuePredicate(String key, String value) {
super();
this.key = key;
this.value = value;
}
#Override
public boolean apply(Map<String, String> arg0) {
// TODO Auto-generated method stub
return arg0.get(key).equals(value);
}
}
return Iterables.any(l2, new Predicate<Map<String, String>>() {
#Override
public boolean apply(Map<String, String> input) {
return input.get("lname").equals("Jordan");
}
});
But you're using maps when you should use objects with properties.
Of course, if you need to do that multiple times, with various properties, you should transform the predicate into a non-anonymous, reusable class:
return Iterables.any(l2, new KeyValuePredicate("lname", "Jordan"));
You can implement an appropriate Predicate and use Iterables.any():
public Predicate<Map<String, String>> withEntry(final String key, final String value) {
return new Predicate<Map<String, String>>() {
public boolean apply(Map<String, String> input) {
return value.equals(input.get(key));
}
};
}
System.out.println(Iterables.any(l2, withEntry("lname", "Jordan")));
Well this is straightforward.
You should create a proper entity class:
public class Person {
private String fName;
private String lName;
private String nName;
public Person(String fName, String lName, String nName) {
this.fName = fName;
this.lName = lName;
this.nName = nName;
}
public String getFName() {
return fName;
}
public String getLName() {
return lName;
}
public String getNName() {
return nName;
}
}
Then you can do the following:
import java.util.*;
public class Test {
public static void main (String [] args) {
List<Person> list = new ArrayList<Person>();
Person p1 = new Person("Mickael", "Jordan", "His Airness");
for (Person person : list) {
if (person.getFName().equals("Mickael")) {
System.out.println("Mickael is in the list!");
break;
}
}
}
}
I am reading two csv files containg a set of attributes
File 1 attributes = name, class, rollno,
File 2 attributes = rollno, city,town
I need to match the two files and for every matching rollno I have to append the File 2 attributes into File1 and create a csv file in the format
rollno, name, class, city, town
So far I have succeeded in reading the File1 and file2 values into a List of linked hashmaps of the type.
List<Map<Object, Object>> _students = new ArrayList<Map<Object, Object>>();
I am not able to figure out the steps to move forward.
How do I search through the list map of first file for the roll no contained in the second listmap and append it to the firstlistmap?
and then print it to a csv file in the order specified ( I am able to iterate and print all the values in the order they were inserted in the map)
I would approach this problem by reading the first file and store the values in a hashmap. and then append to that hashmap
The key would be the role number and the value would be a list of the the other values.
Map<String, List<String>> map = new HashMap<String, List<String>>()
Pseudocode:
for (List<String> line : file1.lines) {
List curLine = new LinkedList();
curLine.add(line.get(0));
curLine.add(line.get(1));
map.put(line.get(2),curLine)
}
for (List<String> line : file2.lines) {
String key = line.get(0);
String list = map.get(key);
if (list != null)
{
list.add(line.get(1));
list.add(line.get(2));
}
map.put(key,list); // probably not necessary as you change the reference that is already in the map, but I'm not sure
}
Load the second file into a Map keyed by rollno This way you can lookup the details which match a rollno using the get() method.
Assuming, you managed to load the contents of both files into practical datastructures:
List<String[]> file1 = loadFile1(); // each item is a String array {name, class, rollNo}
List<String[]> file2 = loadFile2(); // each item is a String array {rollNo, city, town}
then create a map like this:
// sorted map
Map<String, String[]> result = new TreeMap<String, String[]>();
// create a map entry for each roll nr of first file, add name and class
for (String[] file1Item : file1) {
result.put(file1Item[0], new String[4] {file1Item[1], file2Item[2], "", ""});
}
// add the values from list 2
for (String[] file2Item : file2) {
String[] value = result.get(file2Item[2]);
if (value != null) {
value[2] = file2Item[1];
value[3] = file2Item[2];
}
}
Now you have a map like this:
rollno -> [name, class, city, town]
Try this complete code it will work
import java.util.HashMap;
import java.util.Map;
import com.csvreader.CsvReader;
public class ListMap {
public static void main(String args[]) throws Exception {
Map<String, ListMap> map = new HashMap<String, ListMap>();
CsvReader reader = null;
reader = new CsvReader("c:/list1.csv");
reader.readHeaders();
while (reader.readRecord()) {
map.put(reader.get("RollNo"), new ListMap(reader.get("RollNo"),
reader.get("Name"), reader.get("Class"),
reader.get("City"), reader.get("Town")));
}
reader = new CsvReader("c:/list2.csv");
reader.readHeaders();
while (reader.readRecord()) {
ListMap obj = map.get(reader.get("RollNo"));
if (obj != null) {
obj.setCity(reader.get("City"));
obj.setTown(reader.get("Town"));
} else {
obj = new ListMap(reader.get("RollNo"), reader.get("Name"),
reader.get("Class"), reader.get("City"), reader
.get("Town"));
}
map.put(reader.get("RollNo"), obj);
}
for (Map.Entry<String, ListMap> entry : map.entrySet()) {
ListMap obj = entry.getValue();
System.out.println(entry.getKey() + " " + obj.name + " "
+ obj.className + " " + obj.city + " " + obj.town);
}
}
private String roolNo, name, className, city, town;
public ListMap(String roolNo, String name, String className, String city,
String town) {
super();
this.roolNo = roolNo;
this.name = name;
this.className = className;
this.city = city;
this.town = town;
}
public String getRoolNo() {
return roolNo;
}
public void setRoolNo(String roolNo) {
this.roolNo = roolNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}