How to convert List object to string in java [duplicate] - java

This question already has answers here:
How to get the first element of the List or Set? [duplicate]
(9 answers)
Closed 3 years ago.
How do I get the string value from below snippet:
List<Map<String, Object>> list1= (List<Map<String, Object>>) mymap.get("getProduct");
Map<String, Object> myList= list1.get(0);
List<String> myproduct= (List<String>) myList.get("productName");
System.out.println("value " +myproduct.toString());
When I try to print this I'm always getting as an object instead of plain string.
My Output:
[Apple]
Expected output:
Apple
I'm very new to Java, any help would be really appreciated.

Because myproduct is List with string values, for example below is list with fruit names
List<String> fruits = new ArrayList<>();
list.add("apple");
list.add("mango");
System.out.println(fruits); //[apple,mango]
If you want each value from list you can simply iterate using for each loop
for(String str : myproduct) {
System.out.println(str);
}
If you just need first element you can get by index, but might end up with index out of bound exception if list is empty
String ele = myproduct.get(0);
or by using java-8 stream
String ele = myproduct.stream().findFirst().orElse(null);

Related

How to add two lists as attributes to an array of objects in APEX class [duplicate]

This question already has answers here:
Combine two lists of same size (and different type) into list of domain objects using java streams
(2 answers)
How do I combine two lists with the same amount of elements in Java?
(5 answers)
Closed 10 days ago.
How to add two List<String> as array of object attributes
I have two List<String> containing Names and Email Ids. How to add them to an array of objects.
For Ex:
List<String> list1= ['acc1','acc2','acc3','acc4'];
List<String> list2= ['acc1#abc.com','acc2#def.com','acc3#prq.com','acc4.xyz.com'];
I'm looking for an array of objects that look something like below:
Expected Result:
[{'name':'acc1','email':'acc1#abc.com'},{'name':'acc2','email':'acc2#def.com'},{'name':'acc3','email':'acc3#pqr.com'},{'name':'acc4','email':'acc3#xyz.com'}]
Actual result I'm getting:
[{'name':'acc1','email':'acc1#abc.com'},{'name':'acc1','email':'acc2#def.com'},{'name':'acc1','email':'acc3#pqr.com'},{'name':'acc1','email':'acc3#xyz.com'},{'name':'acc2','email':'acc1#abc.com'},{'name':'acc2','email':'acc2#def.com'},{'name':'acc2','email':'acc3#pqr.com'},{'name':'acc2','email':'acc3#xyz.com'},{'name':'acc3','email':'acc1#abc.com'},{'name':'acc3','email':'acc2#def.com'},{'name':'acc3','email':'acc3#pqr.com'},{'name':'acc3','email':'acc3#xyz.com'},{'name':'acc4','email':'acc1#abc.com'},{'name':'acc4','email':'acc2#def.com'},{'name':'acc4','email':'acc3#pqr.com'},{'name':'acc4','email':'acc3#xyz.com'}]
I tried in below code by looping on the two lists but it gives me a different result.
List<ContactWrapper> contactList = new List<ContactWrapper>();
List<String> contEmail = ['acc1','acc2','acc3','acc4'];
List<String> contName = ['acc1#abc.com','acc2#def.com','acc3#prq.com','acc4.xyz.com'];
for(String cEmail: contEmail){
for(String cName: contName){
ContactWrapper cWrap = new ContactWrapper();
cWrap.contactEmail = cEmail;
cWrap.contactName = cName;
contactList.add(cWrap);
}
}
public class ContactWrapper{
public String contactEmail;
public String contactName;
}
I cannot user Java streams as I'm writing the code in APEX

How to use stream to get id from array of object in List? [duplicate]

This question already has an answer here:
Filter an object list based on Integerlist [closed]
(1 answer)
Closed 2 years ago.
Suppose i have list of objects in java which contain ids and name , how can i pick only id and save it into another list
details[{id:1,name:brown},{id:2,white},{id:3,name:black}]
I want is all the ids into the new List.
what i tried is
List<String> ids = details.stream().filter(item -> item.getId()).collect(Collectors.toList());
This throws syntax error near item.getId()
Instead of using .filter, you need to use .map.
To make your code a bit cleaner, you can replace item -> item.getId() with a method reference: Item::getId.
This would be the end result:
List<String> ids = details.stream()
.map(Item::getId)
.collect(Collectors.toList());
The sample works for you,
Employee emp1 = new Employee(1,"Ally");
Employee emp2 = new Employee(2,"Billy");
ArrayList<Employee> employeeList = new ArrayList<>(Arrays.asList(emp1,emp2));
List<Integer> collect = employeeList.stream()
.map(Employee::getId)
.collect(Collectors.toList());
System.out.println("collect = " + collect);

add String to a List of Objects in Java [duplicate]

This question already has answers here:
Run piece of code contained in a String
(9 answers)
Closed 3 years ago.
List<PhoneBook> list = new ArrayList<PhoneBook>();
String str = "new PhoneBook("David","234567");";
How can I add (or convert) str to code and add it to the list?
I have searched all over the internet, and didn't find anything helpful.
To convert it to fit the arraylist you've given:
List<PhoneBook> list = new ArrayList<>();
PhoneBook not_a_str = new PhoneBook("David","234567");
list.add(not_a_str);
To add strings to a list of objects:
List<Object> list = new ArrayList<>();
String str = "new PhoneBook(\"David\",\"234567\")";
list.add(str);
To add strings to a list of strings (also objects):
List<String> list = new ArrayList<>();
String str = "new PhoneBook(\"David\",\"234567\")";
list.add(str);
list.add("Anything else");
Good luck with java

How do you get rid of repeating numbers in a Java array? [duplicate]

This question already has answers here:
How to get unique values from array
(13 answers)
Array of unique elements?
(6 answers)
Closed 3 years ago.
Suppose in an array, there is the numbers {1,1,1,1,1,5}
How do I write a program that does not specifically relate to the numbers(ex. no printing {1,5}) that gets rid of all the repeating numbers in this array?
In other words, if the problem was {a,b,c,d,e} and I without me knowing the numbers inside, how do I write a program in Java that gets rid of all the repeating digits?(the example on the very top's answer would be {1,5})
If you want to keep only unique element you can use a set.
// Generic function to convert list to set
public static <T> Set<T> convertListToSet(List<T> list)
{
// create a set from the List
return list.stream().collect(Collectors.toSet());
}
public static void main(String args[])
{
// Create a stream of integers
List<String> list = Arrays.asList("GeeksForGeeks",
"Geeks",
"forGeeks",
"A computer portal",
"for",
"Geeks");
// Print the List
System.out.println("List: " + list);
// Convert List to stream
Set<String> set = convertListToSet(list);
// Print the Set
System.out.println("Set from List: " + set);
}
the example is taken from here.
If you need it to be a list you can convert it back with:
List<String> aList = new ArrayList<String>(set);

How to convert object class to arrayList ? java [duplicate]

This question already has answers here:
How do I convert a Map to List in Java?
(13 answers)
Closed 8 years ago.
I have this code :
ArrayList<Integer> users = new ArrayList<Integer>();
Map <String,Object> hashMap = new HashMap <String,Object> ();
hashMap.put("users",user);
// now I want to get users as array list
hashMap.get("users")[i];//error
How to users as array ? thank you
List<Integer> users = new ArrayList<Integer>();
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("users",user);
....
....
....
List<Integer> users = (List<Integer>)hashMap.get("users"); //assuming this is another method and 'users' is not defined here yet
Integer[] usersArray = users.toArray(new Integer[users.size()]);
System.out.println("" + usersArray[i]);
Please note that this is an atrocity and you shouldn't be storing that List as an Object, you are pretty much circumventing what Generics are for.
This code will work if you want to access it as an ArrayList:
List<Integer> users = new ArrayList<Integer>();
Map<String, List<Integer>> hashMap = new HashMap<String, List<Integer>> ();
hashMap.put("users",users);
hashMap.get("users");
Your code won't work since you were storing it as an Object. So you would need a cast. And even then you use [] for arrays, not ArrayLists
If you want to use it as an array you can change the last line to:
hashMap.get("users").toArray()
And then you can use [1], or just do .get(1) on the initial code.
Alternatively, if you want to use hashMap as a property bag as someone validly mentioned you would need to do a cast:
((ArrayList<Integer>) hashMap.get("users"))
Then you can use users as an ArrayList as you are getting an Object by default from the HashMap.
You can try something like following
List<Users> usersList = new ArrayList<>();
Map<String,List<Users>> hashMap = new HashMap <> ();
hashMap.put("user",usersList);
Now
hashMap.get("user")
Will return a List of Users, Now you can use
hashMap.get("user").get(0); // to get 0th index user
Because it is ArrayList and not array,You can get it like this-
public static void main(String args[]) throws Exception
{
ArrayList<Integer> users = new ArrayList<Integer>();
users.add(5);
users.add(10);
Map <String,Object> hashMap = new HashMap <String,Object> ();
hashMap.put("users",users);
ArrayList<Integer> no = ((ArrayList<Integer>) hashMap.get("users"));
for (Integer integer : no) {
System.out.println(integer);
}
}
output-
5
10
Now to convert ArrayList to Array -
Integer[] arr = no.toArray(new Integer[no.size()]);

Categories

Resources