I am using this class to manipulate some data using Java:
private static Set<Entry<String, String>> flatten(Map<String, List<String>> map) {
return map.entrySet().stream().flatMap(e ->
e.getValue().stream().map(v -> Map.entry(e.getKey(), v))
)
.collect(Collectors.toSet());
}
However, when I try to compile on eclipse/intellij, I am getting this error:
Cannot resolve method 'entry' in 'Map'
As you can see on the code below, everything is working fine:
https://www.online-java.com/4LblEuqTN6
My code on eclipse is the following:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.*;
import java.util.Set;
import java.util.stream.Collectors;
#RestController
#RequestMapping(value="test")
public class HelloController extends BaseExtController {
private static Set<Entry<String, String>> flatten(Map<String, List<String>> map) {
return map.entrySet().stream().flatMap(e ->
e.getValue().stream().map(v -> Map.entry(e.getKey(), v))
)
.collect(Collectors.toSet());
}
private static Map<String, List<String>> group(Set<Map.Entry<String, String>> entries) {
return entries.stream().collect(Collectors.groupingBy(
Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));
}
#RequestMapping (value="sync", method = RequestMethod.GET
, produces=MediaType.APPLICATION_JSON_VALUE)
public Map<String, List<String>> syncForms(
Model model,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, List<String>> dictOP = new HashMap<String, List<String>>();
Map<String, List<String>> dictMobile = new HashMap<String, List<String>>();
List<String> obj1Mobile = new ArrayList<String>();
List<String> obj1Op = new ArrayList<String>();
obj1Mobile.add("Argentina");
obj1Op.add("Argentina");
dictOP.put("obj1", obj1Op);
dictMobile.put("obj1", obj1Mobile);
Set<Entry<String, String>> mobileEntries = flatten(dictMobile);
Set<Entry<String, String>> opEntries = flatten(dictOP);
Set<Entry<String, String>> add = new HashSet<>(opEntries);
add.removeAll(mobileEntries);
Set<Entry<String, String>> remove = new HashSet<>(mobileEntries);
remove.removeAll(opEntries);
return group(add);
}
Do you guys know why this is happening ? Am I defining some wrong type ?
Related
I want to repalce here time value for all iteration
List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
Map myMap1=new HashMap();
myMap1.put("name", "jai");
myMap1.put("time", Instant.now());
mapList.add(myMap1);
Map myMap2=new HashMap();
myMap2.put("name", "kishan");
myMap2.put("time", Instant.now());
use remove("time") to return old value and put to new key
mapList.forEach(map ->{
map.put("new time",map.remove("time"));
});
I got the answer
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HelloWorld {
public static void main(String... args) {
List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
Map<String, Object> myMap1=new HashMap<String, Object>();
myMap1.put("name", "jai");
myMap1.put("time", Instant.now());
mapList.add(myMap1);
Map<String, Object> myMap2=new HashMap<String, Object>();
myMap2.put("name", "kishan");
myMap2.put("time", Instant.now());
mapList.add(myMap2);
System.out.println(mapList);
mapList.forEach(oneMap -> replaceKeyBy(oneMap));
System.out.println(mapList);
}
private static void replaceKeyBy(Map<String, Object> map) {
map.replace("time",Instant.now().plus(10, ChronoUnit.DAYS));
}
}
i have a class which contains reading a property file through spring.
Property file name sample.properties:
Properties contains:
a=A1
b=B1
etc.,
So i am reading easily through env variable.
So i need this thing two purpose , One is Key Value and second is Value as key , key as Value(vice-versa)
Hence, i added a method to put key as vaule and value as key in Map.
The problem, its not putting values in map, so everything null. i am guessing #postConstruct is may be problem?
and PropLoaderUtils class nowhere added in bean file. But howvever, i am getting value in env .
#Component
#Configuration
#PropertySource(name = "props", value = {
"classpath:config/sample.properties"
})
public class PropLoaderUtils {
#Autowired
private Environment env;
private Map<String, String> valueAsKeyMap = new HashMap<String, String>();
#PostConstruct
private void setPropertyKeys() {
Iterator<?> itr = ((AbstractEnvironment) env).getPropertySources().iterator();
Map<String, Object> map = new HashMap<String, Object>();
while (itr.hasNext()) {
PropertySource propertySource = (PropertySource) itr.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
for (Entry<String, Object> entry : map.entrySet()) {
valueAsKeyMap.put(entry.getValue().toString(),entry.getKey());
}
}
public String getProperty(String key) {
String prop = env.getProperty(key);
return prop;
}
public String getPropertyKeyAsValues(String value) {
return valueAsKeyMap.getProperty(value);
}
}
It is working fine after few changes. please find below :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import java.util.*;
import java.util.Map.Entry;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.MapPropertySource;
import javax.annotation.PostConstruct;
#Configuration
#PropertySource(value = {
"classpath:config/sample.properties"
})
public class PropLoaderUtils {
#Autowired
private Environment env;
private Map<String, String> valueAsKeyMap = new HashMap<String, String>();
#PostConstruct
private void setPropertyKeys() {
Iterator<?> itr = ((AbstractEnvironment) env).getPropertySources().iterator();
Map<String, Object> map = new HashMap<String, Object>();
while (itr.hasNext()) {
org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) itr.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
for (Entry<String, Object> entry : map.entrySet()) {
valueAsKeyMap.put(entry.getKey(), entry.getValue().toString());
}
valueAsKeyMap.entrySet().forEach(entry -> System.out.println("key "+entry.getKey()+" value "+entry.getValue()));;
}
}
Output:
key a value A1
key b value B1
I have a JSON I want a to convert it to a HashMap. I have the following code -
ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonData = new HashMap<String, String>();
jsonData = mapper.readValue(userPropertyJson, new TypeReference<HashMap<String,String>>(){});
it is working fine if the input JSON is
{"user":1, "entity": "email"}
but fails when the JSON is as below -
{"user":1, "entity": ["email","fname","lname","phone"]}
How do I map to HashMap for array also?
Declare a generic HashMap with String as a key and Object as a value , since you don't know the type of value exactly.
Map<String, Object>
And beware of assigning wrong types while retrieving data
Use Map<String, Object>. Example
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonParser {
public static void main(String[] args) {
String userPropertyJson = "{\"user\":1, \"entity\": [\"email\",\"fname\",\"lname\",\"phone\"]}";
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> jsonData = new HashMap<String, Object>();
jsonData = mapper.readValue(userPropertyJson, new TypeReference<HashMap<String,Object>>(){});
System.out.println(jsonData);
} catch (JsonParseException e) {
System.out.println(e.getMessage());
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
If you know in advance that your json will always have the same format (a String key mapped to a List<String>, either with a single element or with many elements), then you could use the ACCEPT_SINGLE_VALUE_AS_ARRAY deserialization feature:
ObjectMapper mapper = new ObjectMapper()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
String jsonWithArray =
"{\"user\": 1, \"entity\": [\"email\", \"fname\", \"lname\", \"phone\"]}";
Map<String, List<String>> map1 =
mapper.readValue(
jsonWithArray,
new TypeReference<HashMap<String, List<String>>>() {});
System.out.println(map1); // {user=[1], entity=[email, fname, lname, phone]}
String jsonWithoutArray = "{\"user\": 1, \"entity\": \"email\"}";
Map<String, List<String>> map2 =
mapper.readValue(
jsonWithoutArray,
new TypeReference<HashMap<String, List<String>>>() {});
System.out.println(map2); // {user=[1], entity=[email]}
This enables you to either have an array for the values in your json, or a single element.
Check out http://www.jsonschema2pojo.org/
It allows you to convert json to java object automatically. I use it when I need to create DTOs from a web service for which I don't have java mapping or SDK.
I have the following structure
{
"abc":[
{
"bc":"52",
"gd":"jjksa"
}
]
}
Now I need to create the same structure from the client side and send the data similar like the above format. I am assuming the structure to be something like this.
HashMap<String, ArrayList<HashMap<String, String>>> hashmap = new HashMap<String, ArrayList<new HashMap<String, String>()>>();
HashMap<String, String> obj1 = new HashMap<String, String>();
ArrayList<String> arraylist = new ArrayList<String>();
obj1.put("bc", "52");
obj1.put("gd", "jjksa");
arraylist.add(obj1);
hashmap.put("metrics", arraylist)
Anyone who can help me create the proper map as shown in the above example.
Use a JSON processor such as Jackson:
import org.codehaus.jackson.map.ObjectMapper;
// ...
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(hashmap);
The below code worked for me. However the suggestion that you guys have put forward is surely valuable. I will make the changes accordingly to make the structure better.
HashMap<String, Object> hashmap = new HashMap<String, Object>();
HashMap<String, String> obj1 = new HashMap<String, String>();
ArrayList arraylist = new ArrayList();
obj1.put("bc", "52");
obj1.put("gd", "jjksa");
arraylist.add(obj1);
hashmap.put("metrics", arraylist);
Gson json = new Gson();
System.out.print(json.toJson(hashmap));
Simple the HashMap's toString method prints the value excatly like your json but without the double-quotes("). :)
sp00m's answer works perfectly. In addition to that you could also use google's Gson.
import java.util.ArrayList;
import java.util.HashMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
public class GsonParser {
public static void main(String[] args) throws Exception {
HashMap<String, ArrayList<HashMap<String, String>>> hashmap = new HashMap<String, ArrayList<HashMap<String, String>>>();
HashMap<String, String> obj1 = new HashMap<String, String>();
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
obj1.put("bc", "52");
obj1.put("gd", "jjksa");
arraylist.add(obj1);
//Hashmap toString
hashmap.put("metrics", arraylist);
System.out.println(hashmap); //Prints : {metrics=[{bc=52, gd=jjksa}]}
//Jackson Example
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(hashmap);
System.out.println(json); //Prints : {"metrics":[{"bc":"52","gd":"jjksa"}]}
//Gson Example
Gson gson = new Gson();
String json2 = gson.toJson(hashmap);
System.out.println(json2); //Prints : {"metrics":[{"bc":"52","gd":"jjksa"}]}
}
}
I'm using IndexTank with the Java client, but I can't seem to access the results:
SearchResults results = index.search(Query.forString(keywords));
for (Map<String, Object> document : results.results) {
System.out.println("doc id: " + document.get("docid"));
The last line fails with: Type mismatch: cannot convert from Object to String
Does anyone know why I get this error? Thanks.
What you have looks fine. Are you sure you're importing all of the right classes? This works for me:
import java.util.HashMap;
import java.util.Map;
import com.flaptor.indextank.apiclient.Index;
import com.flaptor.indextank.apiclient.IndexTankClient;
import com.flaptor.indextank.apiclient.IndexTankClient.Query;
import com.flaptor.indextank.apiclient.IndexTankClient.SearchResults;
public class IndexTankExample {
public static void main(String[] args) throws Exception {
IndexTankClient client = new IndexTankClient("<PRIVATE URL>");
Index index = client.getIndex("test");
Map<String, String> fields = new HashMap<String, String>();
fields.put("text", "foo bar baz");
index.addDocument("1", fields);
SearchResults results = index.search(Query.forString("bar"));
for (Map<String, Object> document : results.results) {
System.out.println("doc id: " + document.get("docid"));
}
}
}