Convert List<Object> to List<String> without for? - java

How can I convert a List of Objects to corresponding List of Strings without scanning all elements by for loop?

You could try this:
List<String> variable = (List<String>)(List<?>) yourList;

In the comments you specified that you wanted to call the toString() method. This is possible with guava (https://code.google.com/p/guava-libraries/):
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
public class Application {
public static void main(String[] args) {
Function<Object, String> objectToString = new Function<Object, String>() {
public String apply(Object object) {
return object.toString();
}
};
List<Object> yourList = new ArrayList<Object>();
yourList.add("foo");
List<String> strings = Lists.transform(yourList, objectToString);
}
}

Related

DynamoDBTypeConverted doesn't work in Java

Logs throw
Converter not found for EnhancedType(java.util.ArrayList<domains.requirementsAndDefinitionForTracingEvents.Event>)
error.
I decided to write a custom converter
package converters;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter;
import domains.requirementsAndDefinitionForTracingEvents.Event;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EventListToMapConverter implements DynamoDBTypeConverter<List<Map<String, ?>>, List<Event>> {
#Override
public List<Map<String, ?>> convert(List<Event> events) {
List<Map<String, ?>> convertedList = new ArrayList<>();
for(Event e: events) {
Map map = new HashMap<>();
map.put("eventCode", e.getEventCode());
map.put("remark", e.getRemark());
map.put("requiredOwn", e.isRequiredOwn());
convertedList.add(map);
}
return convertedList;
}
#Override
public List<Event> unconvert(List<Map<String, ?>> stringStringMap) {
List<Event> convertedList = new ArrayList<>();
for(Map<String, ?> map: stringStringMap) {
Event e = new Event();
e.setEventCode((String) map.get("eventCode"));
e.setRemark((String) map.get("remark"));
e.setRequiredOwn((Boolean) map.get("requiredOwn"));
convertedList.add(e);
}
return convertedList;
}
}
I added it like this
package domains.requirementsAndDefinitionForTracingEvents;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverted;
import converters.EventListToMapConverter;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import java.util.ArrayList;
#DynamoDbBean
public class RequirementsAndDefinitionForTracingEvents {
public RequirementsAndDefinitionForTracingEvents() {
}
public RequirementsAndDefinitionForTracingEvents(ArrayList<Event> tracingEventCodes, AdditionalRules additionalRules) {
this.tracingEventCodes = tracingEventCodes;
this.additionalRules = additionalRules;
}
#DynamoDBTypeConverted(converter = EventListToMapConverter.class)
private ArrayList<Event> tracingEventCodes;
private AdditionalRules additionalRules;
public AdditionalRules getAdditionalRules() {
return additionalRules;
}
public ArrayList<Event> getTracingEventCodes() {
return tracingEventCodes;
}
public void setTracingEventCodes(ArrayList<Event> tracingEventCodes) {
this.tracingEventCodes = tracingEventCodes;
}
public void setAdditionalRules(AdditionalRules additionalRules) {
this.additionalRules = additionalRules;
}
}
but actually nothing changed. Still the same error. What's the problem in here?
I heard of another thing which are converted properties in
#DynamoDBBean attribute but it is quite hard to understand for me if I want to map List<Map<String, ?>>
Also I have seen that #DynamoDBConvertedType is usually used with #DynamoDBDocument but couldn't find any proper for me documentation. I have template.yaml file where I define table name which can be 'TABLE_NAME'. Then do I define #DynamoDBTable attribute on the main object with TableName = 'TABLE_NAME' ?
Should I mark every child class as #DynamoDBDocument? Will it work or it doesn't matter if I use dynamodbbean or dynamodbdocument if I still parse my JSON file with a gson parser?
Well, just needed to change ArrayList to List :- )

GSON: Serialize object with java.util.TreeSet

How can I serialize a TreeSet properly? In order to give you an idea of what's not working I've set up this little demo project. The main goal is to print a JSON string of my QData object.
App.java
package de.company.gsonserializer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class App
{
public static void main( String[] args )
{
QData qdata = new QData();
ArrayList<LData> arrayList = new ArrayList<LData>(1);
LData l = new LData();
Map<String, String> unsortedBuabList = new HashMap<String, String>();
for (int i = 0; i < 5; i++) {
unsortedBuabList.put("Key-" + i, "Value" + i);
}
SortedSet<Map.Entry<String, String>> sortedBuabList = new TreeSet<Map.Entry<String, String>>(
new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedBuabList.addAll(unsortedBuabList.entrySet());
l.setBuabList(sortedBuabList);
arrayList.add(l);
qdata.setLocations(arrayList);
System.out.println( qdata.toString() );
}
}
QData.java
package de.it2media.gsonserializer;
import java.util.ArrayList;
import com.google.gson.Gson;
public class QData {
private ArrayList<LData> locations = new ArrayList<LData>(0);
public ArrayList<LData> getLocations() {
return locations;
}
public void setLocations(ArrayList<LData> locations) {
this.locations = locations;
}
#Override
public String toString(){
Gson gson = new Gson();
String thisObj = gson.toJson(this);
return thisObj;
}
}
LData.java
package de.it2media.gsonserializer;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Map.Entry;
public class LData {
private SortedSet<Entry<String, String>> buabList = new TreeSet<Map.Entry<String, String>>();
public SortedSet<Entry<String, String>> getBuabList() {
return buabList;
}
public void setBuabList(SortedSet<Entry<String, String>> buabList) {
this.buabList = buabList;
}
}
The output: {"locations":[{"buabList":[{},{},{},{},{}]}]}
Expected output would be something like: {"locations":[{"buabList":[{"key":"Key-0","value":"Value0"},{"key":"Key-1","value":"Value1"},{"key":"Key-2","value":"Value2"},{"key":"Key-3","value":"Value3"},{"key":"Key-4","value":"Value4"}]}]}
Do you might know why GSON is not working as I'd expect it to work?
Thanks for any help, highly appreciated!
The problem you are running into has nothing to do with the TreeSet, but rather with the fact that GSON does not know how to serialize a map Entry in the way that you would like. You therefore need to write a custom serializer for it, which looks something like this:
public static class EntrySerializer implements JsonSerializer<Entry<String, String>> {
#Override
public JsonElement serialize(Entry<String, String> entry, Type typeOfSrc, JsonSerializationContext context) {
JsonElement serializedKey = context.serialize(entry.getKey());
JsonElement serializedValue = context.serialize(entry.getValue());
JsonObject jsonObject = new JsonObject();
jsonObject.add("key", serializedKey);
jsonObject.add("value", serializedValue);
return jsonObject;
}
}
When you create the Gson object, you then need to register this custom serializer:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Entry.class, new EntrySerializer())
.create();
You can read more about custom serializers and deserializers in the GSON documentation.

How to add List of objects in a Map

I have a List and A is defined below.
How do i add in a Map with Key as Long and values as List of Strings.
Class A
{
Long in;
List<String> out;
}
Map<Long,List<String>>
Create a Hashmap object, with key Long and value List. Add items with put(key,value) and retrieve them with get
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Long,List<String>> myMap=new HashMap<Long,List<String>>();
List<String> myList=new ArrayList<String>();
myList.add("abc");
myList.add("xyz");
myMap.put(new Long(1), myList);
for(int i=0;i<myList.size();i++)
System.out.println(myMap.get(new Long(1)).get(i));
}
}
1.) Create HashMap with Key as Long and value as List<String>.
2.) Use put method of HashMap, as below.
public static void main(String[] args) {
Map<Long, List<String>> myMap = new HashMap<Long, List<String>>();
myMap.put(101L, new ArrayList<String>());
}

How to Sort HashMap <String ,Object> using Object Value

I'm having trouble applying sorting mechanism through my application.
Reason was sometimes sort are not accurate and also the comparator thing in java still not clear for me, but i have used sort here and there.
Now, current problem is as follows.
I have
HashMap<String, ModelX.ContactModel> unsortedModelContacts =
new HashMap<String,ModelX.ContactModel>(contacts.size());
After that I fached
contactlist and using for loop I have put the values as follows:
unsortedModelContacts.put(stringvalue, modelContact);
//object having name , and other details
How can I sort the unsortedModelContacts sorting modelContact.getName property?
If your map's key is different from the name field then you can consider using this approach. Writing a separate comparator
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import sample.ModelX.ContactModel;
public class SortMapSample {
public static void main(String[] args) throws Exception {
Map<String, ModelX.ContactModel> unsortedModelContacts = new HashMap<String,ModelX.ContactModel>(10);
unsortedModelContacts.put("1", new ModelX.ContactModel("James"));
unsortedModelContacts.put("2", new ModelX.ContactModel("Mary"));
unsortedModelContacts.put("3", new ModelX.ContactModel("John"));
unsortedModelContacts.put("4", new ModelX.ContactModel("Amanda"));
unsortedModelContacts.put("5", new ModelX.ContactModel("Charles"));
System.out.println(sortMap(unsortedModelContacts));
}
private static Map<String, ModelX.ContactModel> sortMap(
Map<String, ModelX.ContactModel> unsortedMap) {
List<Entry<String, ModelX.ContactModel>> list = new LinkedList<Entry<String, ModelX.ContactModel>>(
unsortedMap.entrySet());
Collections.sort(list,
new Comparator<Entry<String, ModelX.ContactModel>>() {
#Override
public int compare(Entry<String, ContactModel> o1,
Entry<String, ContactModel> o2) {
return o1.getValue().getName().compareTo(o2.getValue().getName());
}
});
Map<String, ModelX.ContactModel> sortedMap = new LinkedHashMap<String, ModelX.ContactModel>();
for(Entry<String, ModelX.ContactModel> item : list){
sortedMap.put(item.getKey(), item.getValue());
}
return sortedMap;
}
}
SortedMap<String,ModelX.ContactModel> sortedModelContacts = new TreeMap<>();
for( ModelX.ContactModel modelContact: contactlist ){ // same list as before
sortedModelContacts.put( modelContact.getName(), modelContact);
}
You can now access entries of this map in sort order of the name property.
Note: this assumes that names are unique. If this isn't true, you'll have to use a multimap or
Map<String,ModelX.Set<ContactModel>>
and modify the put and other accesses accordingly.

Java create list problems with List<Type> myList = new ArrayList<Type>();

I want to create list by doing this
List<String> myList = new ArrayList<String>();
but it's not recognized, i don't know why:
Eclipse suggest me to modify the syntax :
First eclipse consider that the type List is not generic and it removes the first String brackets
List myList = new ArrayList<String>();
and then change the type of my List and finally i have :
ArrayList<String> myList = new ArrayList<String>();
I really don't understand why it doesn't work.
How to make a new List in Java
I read this post and try again with an other type it's the same problem.
EDIT:my code look like this
import java.util.ArrayList;
import java.awt.List;
public class Test {
public static void main(String[] args){
List<String> myList = new ArrayList<String>();
}
}
The problem was solved by changing
import java.awt.List;
to
import java.util.List;
Does your code look like this?
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) throws Exception {
List<String> myList = new ArrayList<String>();
}
}

Categories

Resources