Add 2 arraylists into 1 with same index value - java

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();
}

Related

How can I fill up the list in to my HashMap? [duplicate]

This question already has answers here:
How to call a method in another class of the same package?
(8 answers)
Closed 2 years ago.
first I have three classes:
Data.java:
public class Data {
public static List<String> studentdataget(){
List<String> studentData = new ArrayList<String>();
// Format:
// Name ; Number ; Subject
studentData.add("Quee;810283;MathI");
studentData.add("Hor;812227;Math I");
studentData.add("Oper;810369;Math II");
studentData.add("Graf;811090;MathI");
studentData.add("Ingri;811911;MathI");
Student.java:
public class Student {
private static String name = "";
private static int number = 0;
private static String subject = "";
public Student(String name, int number, String subject) {
this.name = name;
this.number = number;
this.subject = subject;
}
public static String getnumber(String segs) {
return number;
}
public static int getnumber(String segs) {
return number;
}
public static String getName() {
return name;
}
public void setsubject(String subject) {
this.subject = subject;
}
public void setnumber(int number) {
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
String returnString = name + " (" + number + "), Subject: " + subject;
return returnString;
}
}
main.java:
public class main {
public static void main(String[] args) {
String path = "Name;number;subject";
String[] segs = path.split( Pattern.quote( ";" ) );
//System.out.println( (segs[2]));
HashMap<String, String> studentData = new HashMap<String, String>();
studentData.put(segs[1],segs[2]);
for (Map.Entry<String, String> pair: studentData.entrySet()) {
System.out.format("key: %s, value: %s\n", pair.getKey(), pair.getValue());
}
for(Map.Entry<String, String> pair: studentData.entrySet()) {
}
}
}
So the question is how can I put in my second for loop the list from my Data.class?
I want to display only the number and the subject is this possible ?
I have try so many ways and no one is getting me to the solution .. I hope someone can give me a solution
To access the studentData method from another class, you can use this notation Data.studentdataget(); since studentdataget() is static.
You just split() on ; in each entry of yout list to split them into [Quee, 810283, MathI]. Therefore you can use the last two indexes to get the desired data.
This assumes all the data in studentData remains uniform.
public static void main(String[] args) {
List<String> students = Data.studentdataget(); // access Data here
HashMap<String, String> classes = new HashMap<>();
// fill our map from the data found in Data.studentdataget
for (String student: students) {
String[] arr = student.split(";"); // split string into array on each ;
classes.put(arr[1], arr[2]); // fill map based on student data set
}
// print the map
for (Map.Entry<String, String> entry : classes.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}

How to create an object with data in Java

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());

Java: Arraylist of Array

I want to make an arraylist of an array of 2 elements. So, I have unknown rows and known columns (i.e. 2).
E.g. [{name1, ID1}, {name2, ID2}, ...]
I also have to return this arraylist.
I tried using
ArrayList<arr> alist = new ArrayList<arr>();
but don't know how to proceed.
Please advise.
When you define a ArrayList must use a class. In this case, you can use a class Person:
class Person {
private Integer id;
private String 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;
}
}
Then, we can define a ArrayList of Persons:
ArrayList<Person> array = new ArrayList<Person>();
array.get(0).getId();
array.get(0).getName();
I have put here two simple ways to do it. However, you can think of many more such ways.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] a) {
List<String[]> list = new ArrayList<>();
String[] arr;
arr = new String[2];
arr[0] = "name1";
arr[1] = "ID1";
list.add(arr);
arr = new String[2];
arr[0] = "name2";
arr[1] = "ID2";
list.add(arr);
// Test
for (String[] arrElem : list) {
System.out.println(arrElem[0] + "\t" + arrElem[1]);
}
// Another option is to create a list of maps
List<Map<String, String>> list2 = new ArrayList<>();
Map<String, String> map = null;
map = new HashMap<>();
map.put("name1", "ID1");
list2.add(map);
map = new HashMap<>();
map.put("name2", "ID2");
list2.add(map);
// Test
for (Map<String, String> mapElem : list2) {
System.out.println(mapElem);
}
}
}
Output:
name1 ID1
name2 ID2
{name1=ID1}
{name2=ID2}

How to get value object inside object from hash map

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"));

search for a key value pair in a list of hash maps

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;
}
}

Categories

Resources