I am trying to convert the following piece of code to use ImmutableSetMultimap, but I run into problems when I try to do map.get(...).add(...) because its immutable. Is there an easy way to do this?
List<MyObject> objects
Map<Long, Set<Key>> map = new HashMap<Long, Set<Key>>();
for (MyObject entry : objects) {
if (map.containsKey(entry.getId())) {
map.get(entry.getId()).add(entry.getKey());
} else {
Set<Key> newSet = new HashSet<Key>();
newSet.add(entry.getKey());
map.put(entry.getId(), newSet);
}
}
ImmutableSetMultimap has a builder:
ImmutableSetMulitimap.Builder<Key, Value> builder = ImmutableSetMulitimap.builder();
for (Entry<Key, Value> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
ImmutableSetMulitimap<Key, Value> map = builder.build();
For more info please see the javadoc
Related
I'm putting in a List<Map<String, Object>> the result of a query along with the column names. Sometimes column names are like TableAlias.ColumnName, in that case I want to change it to just ColumnName and remove TableAlias. for that I have below code:
queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
for (Map<String, Object> map : queryResult) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 0) {
Object obj = map.remove(entry.getKey());
map.put(keyData[1], obj);
}
}
}
That is giving me concurrent modification exception so I was trying with an iterator like below:
for (Map<String, Object> map : queryResult) {
for(Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Object> entry = it.next();
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 0) {
it.remove();
}
}
}
But not sure how to add the item back with the new key.
Any suggestions please?
I would iterate over the original map and fill another map with the updated keys.
queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
Map<String, Object> newMap = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 1) {
newMap.put(keyData[1], entry.getValue());
} else {
newMap.put(entry.getKey(), entry.getValue());
}
}
How can we convert the list and sublist into a single map in java 8?
Sample code
Map<String, String> pepAnswersMap = new HashMap<>();
for (Iterator<PepQuestionsDTO> iterator = pepQuestions.iterator(); iterator.hasNext();) {
PepQuestionsDTO pepQuestion = iterator.next();
pepAnswersMap.put(pepQuestion.getSign(), pepQuestion.getAnswer().getAnswer());
for (Iterator<SubQuestionsDTO> iterator2 = pepQuestion.getSubQuestions().iterator(); iterator2.hasNext();) {
SubQuestionsDTO subQuestion = iterator2.next();
pepAnswersMap.put(subQuestion.getSign(), subQuestion.getAnswer().getAnswer());
}
}
You can do like this:
pepQuestionsDTOS.stream()
.flatMap(pepQuestion -> {
pepAnswersMap.put(pepQuestion.getSing(), pepQuestion.getAnswer().getAnswer());
return pepQuestionsDTO.getSubQuestions().stream();
})
.map(subQuestion -> new AbstractMap.SimpleEntry<>(subQuestion.getSing(),
subQuestion.getAnswer().getAnswer()))
.forEach(entry -> pepAnswersMap.put(entry.getKey(), entry.getValue()));
however I think using of forEach loop is more readable
pepQuestionsDTOS.forEach(pepQuestion->
{
pepAnswersMap.put(pepQuestion.question, pepQuestion.getAnswer());
pepQuestion.getSubQuestions()
.forEach(pepQuestion ->
pepAnswersMap.put(pepQuestion.getSing(), pepQuestion.getAnswer().getAnswer()));
});
I need to fill map with Iterable<Map.Entry>. The following is an original java code:
Iterable<Map.Entry<String, String>> conf;
Iterator<Map.Entry<String, String>> itr = conf.iterator();
Map<String, String> map = new HashMap<String, String>();
while (itr.hasNext()) {
Entry<String, String> kv = itr.next();
map.put(kv.getKey(), kv.getValue());
}
I have to rewrite it in groovy. Is there a concise groovy-way to do it?
I'd use collectEntries for that. It's similar to collect, but it's purpose is to create a Map.
def sourceMap = ["key1": "value1", "key2": "value2"]
Iterable<Map.Entry<String, String>> conf = sourceMap.entrySet()
def map = conf.collectEntries {
[(it.key): it.value]
}
Note the round braces around it.key that allow you to use a variable reference as key of the newly generated Entry.
In Groovy you can use the each closure instead of Iterator as follows
Map<Map.Entry<String, String>> sourceMap = ["key1" : "value1", "key2" : "value2"]
Map<Map.Entry<String, String>> targetMap = [:]
sourceMap.each{ key, value ->
targetMap[key] = value
}
println targetMap
Working example here : https://groovyconsole.appspot.com/script/5100319096700928
Code below seems to work casting map_b to map_a, but is there a better solution?
Map<Integer,List<MyClass>> map_a = new HashMap<>();
Map<Integer,List<Object>> map_b = factory.createMapWithMyClasses();
for(Map.Entry<Integer, List<Object>> entry : map_b.entrySet())
{
map_a.put(entry.getKey(), (List<MyClass>) (List) entry.getValue());
}
You can use ? instead of Object.
Map<Integer,List<MyClass>> map_a = new HashMap<>();
Map<Integer,List<?>> map_b = factory.createMapWithMyClasses();
for(Map.Entry<Integer, List<?>> entry : map_b.entrySet()){
map_a.put(entry.getKey(), (List<MyClass>) entry.getValue());
}
I have an ArrayList of HashMap. I want to search a HashMap in it but unable to find a way to achieve this. Please suggest me how it can be done?
Thanks.
Answer to your question the way i understood it!
for (HashMap<String, String> hashMap : yourArrayList)
{
// For each hashmap, iterate over it
for (Map.Entry<String, String> entry : hashMap.entrySet())
{
// Do something with your entrySet, for example get the key.
String sListName = entry.getKey();
}
}
Your Hashmap might use other types, this one uses Strings.
See if this helps:
#Test
public void searchMap() {
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
String keyToSearch = "key2";
for (Map<String, String> map : listOfMaps) {
for (String key : map.keySet()) {
if (keyToSearch.equals(key)) {
System.out.println("Found : " + key + " / value : " + map.get(key));
}
}
}
}
Cheers!
Object myObj;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if( (myObj = curMap.get(myKey)) != null) {
//Stop traversing because we are done
break;
}
}
//Act on the object
if(myObj != null) {
//TODO: Do your logic here
}
If you are looking to get the reference to the Map instead of the object (for whatever reason) same process applies, except you just store the reference to the map:
Map myMap;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if(curMap.get(myKey) != null) {
//Store instance to the map
myMap = curMap;
//Stop traversing because we are done
break;
}
}
//Act on the map
if(myMap != null) {
//TODO: Do your logic here
}
Try below improved code for searching the key in a list of HashMap.
public static boolean searchInMap(String keyToSearch)
{
boolean returnVal = false;
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
for (Map<String, String> map : listOfMaps)
{
if(map.containsKey(keyToSearch))
{
returnVal =true;
break;
}
}
return returnVal;
}
The Efficient way i've used to search a hashmap in an arraylist without using loops. Since loop makes execution time longer
try{
int index = list.indexOf(map); // map is your map to find in ArrayList
if(index>=0){
HashMap<String, String> map = array_list.get(index);
// Here you can get your values
}
}
catch(Exception e){
e.printStackTrace();
Log.i("HashMap","Not Found");
}
if you have an ArrayList like this one: ArrayList<HashMap<String, String>>
and you want to compare one of the values inside the HashMap try this code.
I use it to compare settings of my alarm notifications.
for (HashMap<String, String> map : AlarmList) {
for (String key : map.keySet())
{
if (key.equals("SendungsID"))
{
if(map.get(key).equals(alarmMap.get("AlarmID")))
{
//found this value in ArrayList
}
}
}
}