Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Map' - 38 code snippet(s) found

 Sample 1. Usage of Apache Commons - ArrayListValuedHashMap

ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");

System.out.println(listValuedMap); // Values being added to the List and allow even duplicates

   Like      Feedback     apache commons  apache commons collections  ArrayListValuedHashMap  ListValuedMap


 Sample 2. Initialize maps through static block

public class CoinChanger {
   private static Map<Currency, Integer> cashBox;
   private static Map<Currency, Integer> change;

enum Currency {
      DOLLAR,QUARTER,DIME,NICKEL,PENNY;
   }

   static {
      cashBox = new TreeMap<Currency, Integer>();
      change = new TreeMap<Currency, Integer>();
      initializeCashBox();
   }

   private static void initializeCashBox(){
      //set the cash box
      cashBox.put(Currency.DOLLAR, 50);
      cashBox.put(Currency.QUARTER, 0);
      cashBox.put(Currency.DIME, 50);
      cashBox.put(Currency.NICKEL, 50);
      cashBox.put(Currency.PENNY, 50);
   }
}
}

   Like      Feedback     static block   enum   initializing maps   initializing treemap


 Sample 3. Usage of LinkedHashMap


Map<String,String> linkedhashmap = new LinkedHashMap();
linkedhashmap.put("United States", "Washington");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("South Africa", "Pretoria");
linkedhashmap.put("South Africa", "Cape Town");
linkedhashmap.put("South Africa", "Bloemfontein");

System.out.println(linkedhashmap); // Duplicates not allowed as it's a Map, Insertion Order as its linked Map

   Like      Feedback     LinkedHashMap  Map  HashMap  java.util  collections framework


 Sample 4. Usage of Apache Commons - HashSetValuedHashMap

SetValuedMap<String,String> setValuedMap = new HashSetValuedHashMap();
setValuedMap.put("United States", "Washington");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("South Africa", "Pretoria");
setValuedMap.put("South Africa", "Cape Town");
setValuedMap.put("South Africa", "Bloemfontein");
      
System.out.println(setValuedMap); // Values being added to the Set and hence doesn't allow duplicates

   Like      Feedback     apache commons   apache commons collections  apache commons map   HashSetValuedHashMap  SetValuedMap


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Write a Program for Graph Depth First Traversal using Apache Commons MultiMap

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Graph {
   private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
   private static Set<Integer> alreadyVisited = new HashSet();
   
   static{
      adjacentDirectedNodesMap.put(1, 2);
      adjacentDirectedNodesMap.put(1, 3);
      adjacentDirectedNodesMap.put(1, 5);
      adjacentDirectedNodesMap.put(2, 4);
      adjacentDirectedNodesMap.put(4, 5);
   }
   
   public static void main(String[] args){
      ArrayList visited = new ArrayList();
      
      Integer startNode = 1;
      
      displayAdjacentNodes(startNode);
      
   }
   
   private static void displayAdjacentNodes(Integer integer){
      if(alreadyVisited.contains(integer)){
         return;
      }
      alreadyVisited.add(integer);
      System.out.println(integer);
      for(Integer adjacentNodes: adjacentDirectedNodesMap.get(integer)){
         displayAdjacentNodes(adjacentNodes);
      }
   }
   
}

   Like      Feedback     graph traversal  depth first algorithm


 Sample 6. Write a Program for Graph Breadth First Traversal using Apache Commons MultiMap

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Graph {
   private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
   private static Set<Integer> alreadyVisited = new HashSet();
   
   static{
      adjacentDirectedNodesMap.put(1, 2);
      adjacentDirectedNodesMap.put(1, 3);
      adjacentDirectedNodesMap.put(1, 5);
      adjacentDirectedNodesMap.put(2, 4);
      adjacentDirectedNodesMap.put(4, 5);
   }
   
   public static void main(String[] args){
      ArrayList visited = new ArrayList();
      
      Integer startNode = 1;
      
      displayAdjacentNodes(startNode);
      
   }
   
   private static void displayAdjacentNodes(Integer integer){
      System.out.println(integer);
      for(Map.Entry<Integer, Collection<Integer>> adjacentNodes: adjacentDirectedNodesMap.asMap().entrySet()){
         for(Integer integer1:adjacentNodes.getValue()){
            if(alreadyVisited.contains(integer1)){
               continue;
            }
            alreadyVisited.add(integer1);
            System.out.println(integer1);
         }
      }
   }
   
}

   Like      Feedback     graph traversal  breadth first traversal


 Sample 7. Create a Map using Set elements using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to get a Map out of Set 

System.out.println(intSet.stream().collect((Collectors.toMap(p->(Integer)p,q->((Integer)q)*500)))); // Prints {1=500, 2=1000, 3=1500, 4=2000} 

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors


 Sample 8. Usage of HashMap

Map<Integer,String> indexedInfo = new HashMap();
indexedInfo.put(1,"Spain");
indexedInfo.put(2,"Denmark");
indexedInfo.put(3,"China");

   Like      Feedback     hashmap  map  collections  java.util.hashmap


 Sample 9. Method to remove duplicates from a Map ( string and List of objects ) by matching the member field of the object.

Map<String,List<ClassInfoBean>> removeDuplicates(Map<String, List<ClassInfoBean>> interfaceMap){
   Map<String, List<ClassInfoBean>> interfaceMapWithoutDuplicate = new HashMap();
      
   for(Map.Entry<String, List<ClassInfoBean>> entry: interfaceMap.entrySet()){
      List<ClassInfoBean> classListWithoutDuplicate = new ArrayList();
      boolean alreadyContain = false;
      for(ClassInfoBean classes: entry.getValue()){
         for(ClassInfoBean classes1: classListWithoutDuplicate){
            if(classes1.name.equalsIgnoreCase(classes.name)){
               alreadyContain = true;
               break;
            }
         }
         if(alreadyContain == false){
            classListWithoutDuplicate.add(classes);
         }
      }
      interfaceMapWithoutDuplicate.put(entry.getKey(), classListWithoutDuplicate);
   }
      
   return interfaceMapWithoutDuplicate;
}

   Like      Feedback     map  map of list of objects  remove duplicates from map  Map.Entry


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Method to get a map of words and their count by passing in the string

Map<String,Integer> wordCountMap = new TreeMap();
String[] words = text.split(" ");
Set<Integer> countSet;
for(String word: words) {
if(wordCountMap.containsKey(word.toLowerCase())){
wordCountMap.put(word.toLowerCase(), wordCountMap.get(word.toLowerCase()).intValue() + 1);
} else {
wordCountMap.put(word.toLowerCase(), 1);
}
}

countSet = new TreeSet(Collections.reverseOrder());
countSet.addAll(wordCountMap.values());

for(Integer inte: countSet) {
for(Entry<String,Integer> entry: wordCountMap.entrySet()){
if(entry.getValue() == inte) {
System.out.println(entry);
}
}
}

   Like      Feedback     map  word count  map of string and integer  containsKey  string split  treeset  Collections.reverseOrder  set addAll   entry


 Sample 11. Controller in Spring MVC

@Controller
@RequestMapping("/employee")
public class EmployeeInfoController {
@RequestMapping(value = "", method = RequestMethod.GET)
public Model searchEmployeeInfo(Model model, @RequestParam("id") String employeeId) {
   // body
}
}

   Like      Feedback     controller  @Controller  @RequestMapping  RequestMethod.GET  @RequestParam  Spring mvc  spring framework


 Sample 12. Initialize member elements ( maps ) using constructor

public class CoinChanger {
   private static Map<Currency, Integer> cashBox;
   private static Map<Currency, Integer> change;

   enum Currency {
      DOLLAR,QUARTER,DIME,NICKEL,PENNY;
   }

   CoinChanger() {
      cashBox = new TreeMap<Currency, Integer>();
      change = new TreeMap<Currency, Integer>();
      initializeCashBox();
   }

   private static void initializeCashBox(){
      //set the cash box
      cashBox.put(Currency.DOLLAR, 50);
      cashBox.put(Currency.QUARTER, 0);
      cashBox.put(Currency.DIME, 50);
      cashBox.put(Currency.NICKEL, 50);
      cashBox.put(Currency.PENNY, 50);
   }
}
}

   Like      Feedback     constructor   initializing maps   initializing treemap   enum


 Sample 13. Loading Cache Map using Google Guava LoadingCache and CacheBuilder

LoadingCache<String,String> loadingCache = CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(new CacheLoader<String,String>(){
   @Override
   public String load(String arg0) throws Exception {
      return "";
   }
});

   Like      Feedback     google guava  loadingcache  CacheBuilder  CacheLoader


 Sample 14. Java 8 Map Merge Example ( Map.merge )

Map<String,String> intMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");
String str = strMap.merge("Key1","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints ue1Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=ue1Value56}

   Like      Feedback     java 8  map.merge  map merge  hashmap  collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Java 8 MapMerge

Map<String,String> strMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");
String str = strMap.merge("Key4","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=Value1, Key4=Value56}

   Like      Feedback     java 8  map.merge  map merge  hashmap  collections


 Sample 16. Clear Map entries after expiration time using Apache commons PassiveExpiringMap

PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1000); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1"));
Thread.sleep(500);
System.out.println(cache.containsKey("Key1"));
Thread.sleep(500);
System.out.println(cache.containsKey("Key1"));

   Like      Feedback     expiring cache using map   Clear Map entries after expiration time   PassiveExpiringMap


 Sample 17. Clear Map entries after expiration time using Apache commons PassiveExpiringMap

PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1,TimeUnit.SECONDS); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1")); // prints true
Thread.sleep(1000);
System.out.println(cache.containsKey("Key1")); // prints false

   Like      Feedback     Clear Map entries after expiration  PassiveExpiringMap  map  apache commons  TimeUnit.SECONDS  Thread.sleep


 Sample 18. Make a map readonly using Apache Commons UnmodifiableMap

Map<String,String> map = new HashMap();
map.put("Key1", "Value1");

Map<String,String> unmodifiableMap = UnmodifiableMap.unmodifiableMap(map);
      
unmodifiableMap.put("Key2", "Value2"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     readonly map  apache commons


 Sample 19. Make a Map entry read only using Apache Commons UnmodifiableMapEntry

Entry entry = new UnmodifiableMapEntry("Key2", "Value2");
entry.setValue("Value3"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     read only map entry  UnmodifiableMapEntry  Apache commons collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Usage of TreeMap

Map<String,String> treemap = new TreeMap();
treemap.put("United States", "Washington");
treemap.put("Canada", "Ottawa");
treemap.put("Canada", "Ottawa");
treemap.put("South Africa", "Pretoria");
treemap.put("South Africa", "Cape Town");
treemap.put("South Africa", "Bloemfontein");

System.out.println(treemap); // Duplicate Not allowed as it's a Map, Ordered by Keys as it's a TreeMap

   Like      Feedback     TreeMap  Map  java.util


 Sample 21. Print all elements of a ListValuedMap ( Apache Commons ) using forEach and System.out::println

ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");

listValuedMap.entries().forEach(System.out::println);

   Like      Feedback     ListValuedMap  apache commons  System.out::println  collections framework   map


 Sample 22. Usage of ConcurrentSkipListMap

Map<String,String> map = new ConcurrentSkipListMap();
map.put("United States", "Washington");
map.put("Canada", "Ottawa");
map.put("Canada", "Ottawa");
map.put("South Africa", "Pretoria");
map.put("South Africa", "Cape Town");
map.put("South Africa", "Bloemfontein");

System.out.println(map); // Prints {Canada=Ottawa, South Africa=Bloemfontein, United States=Washington}
      
// Duplicates not allowed as it's a Map, Sorted as par natural order of keys for faster and concurrent operations.

   Like      Feedback     map  ConcurrentSkipListMap  concurrent access map


 Sample 23. Usage of EnumMap

Map<Country,String> map = new HashMap();
map.put(Country.US, "Washington");
map.put(Country.CANADA, "Ottawa");
map.put(Country.CANADA, "Ottawa");
map.put(Country.SOUTH_AFRICA, "Pretoria");
map.put(Country.SOUTH_AFRICA, "Cape Town");
map.put(Country.SOUTH_AFRICA, "Bloemfontein");

Map<String,String> enumMap = new EnumMap(map); // Prints {CANADA=Ottawa, US=Washington, SOUTH_AFRICA=Bloemfontein}

System.out.println(enumMap); // Duplicates not allowed as it's a Map, Sorted as per order of Enum Declarations

   Like      Feedback     EnumMap  Collections framework  Map  Map with enum keys


 Sample 24. Usage of Apache Commons CaseInsensitiveMap

Map<String, String> map = new CaseInsensitiveMap<String, String>();
map.put("US", "Washington");
map.put("us", "Washington DC");
      
System.out.println(map); // Prints {us=Washington DC} as Keys are case insensitive

   Like      Feedback     CaseInsensitiveMap  Map with Case insensitive keys  apache commons  apache commons collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Code Sample / Example / Snippet of org.apache.hadoop.mapred.TaskTracker.TaskInProgress

  public synchronized boolean statusUpdate(TaskAttemptID taskid, 

TaskStatus taskStatus)

throws IOException {

TaskInProgress tip = tasks.get(taskid);

if (tip != null) {

tip.reportProgress(taskStatus);

return true;

} else {

LOG.warn("Progress from unknown child task: "+taskid);

return false;

}

}


   Like      Feedback      org.apache.hadoop.mapred.TaskTracker.TaskInProgress


 Sample 26. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Counters.Counter

  public synchronized void incrAllCounters(Counters other) {

for (Group otherGroup: other) {

Group group = getGroup(otherGroup.getName());

group.displayName = otherGroup.displayName;

for (Counter otherCounter : otherGroup) {

Counter counter = group.getCounterForName(otherCounter.getName());

counter.displayName = otherCounter.displayName;

counter.value += otherCounter.value;

}

}

}


   Like      Feedback      org.apache.hadoop.mapred.Counters.Counter


 Sample 27. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Mapper

  public void map(Object key, Object value, OutputCollector output,

Reporter reporter) throws IOException {

Mapper mapper = chain.getFirstMap();

if (mapper != null) {

mapper.map(key, value, chain.getMapperCollector(0, output, reporter),

reporter);

}

}


   Like      Feedback      org.apache.hadoop.mapred.Mapper


 Sample 28. Code Sample / Example / Snippet of org.apache.hadoop.mapred.lib.KeyFieldHelper.KeyDescription

  public void setKeyFieldSpec(int start, int end) {

if (end >= start) {

KeyDescription k = new KeyDescription();

k.beginFieldIdx = start;

k.endFieldIdx = end;

keySpecSeen = true;

allKeySpecs.add(k);

}

}




   Like      Feedback     org.apache.hadoop.mapred.lib.KeyFieldHelper.KeyDescription


 Sample 29. Code Sample / Example / Snippet of java.util.Map

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

Map map = (Map) operand;

String host = (String) map.get("host");

String database = (String) map.get("database");

return new MongoSchema(host, database);

}


   Like      Feedback      java.util.Map


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Code Sample / Example / Snippet of com.fasterxml.jackson.databind.ObjectMapper

  public JsonEnumerator(File file) {

try {

final ObjectMapper mapper = new ObjectMapper();

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);

List<Object> list = mapper.readValue(file, List.class);

enumerator = Linq4j.enumerator(list);

} catch (IOException e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      com.fasterxml.jackson.databind.ObjectMapper


 Sample 31. Code Sample / Example / Snippet of org.apache.calcite.schema.SchemaPlus

    public Connection apply(Connection connection) throws SQLException {

if (schema != null) {

CalciteConnection con = connection.unwrap(CalciteConnection.class);

SchemaPlus rootSchema = con.getRootSchema();

rootSchema.add(name, schema);

}

connection.setSchema(name);

return connection;

}


   Like      Feedback      org.apache.calcite.schema.SchemaPlus


 Sample 32. Code Sample / Example / Snippet of org.apache.hc.core5.http.impl.nio.UriHttpAsyncRequestHandlerMapper

    public void testRegisterUnregister() throws Exception {

final HttpAsyncRequestHandler<?> h = Mockito.mock(HttpAsyncRequestHandler.class);



final UriPatternMatcher<HttpAsyncRequestHandler<?>> matcher = Mockito.spy(

new UriPatternMatcher<HttpAsyncRequestHandler<?>>());

final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(matcher);



registry.register("/h1", h);

registry.unregister("/h1");



Mockito.verify(matcher).register("/h1", h);

Mockito.verify(matcher).unregister("/h1");

}


   Like      Feedback      org.apache.hc.core5.http.impl.nio.UriHttpAsyncRequestHandlerMapper


 Sample 33. Given a Map with Country Name as key and its capitals as values, Find the name of countries having more than 1 capital ?

Map<String,List<String>> capitals = new HashMap();
capitals.put("United States", Arrays.asList("Washington DC"));
capitals.put("Canada", Arrays.asList("Ottawa"));
capitals.put("South Africa", Arrays.asList("Pretoria", "Cape Down", "Bloemfontein"));
      
for(Map.Entry<String,List<String>> entry: capitals.entrySet()){
   if(entry.getValue().size() > 1){
      System.out.println(entry.getKey());
   }
}

   Like      Feedback     Map of String and List


 Sample 34. Code Sample / Example / Snippet of java.util.concurrent.Semaphore

    private void removeRepository(String instanceName) throws IOException, InterruptedException, InvalidSyntaxException {

Configuration[] configs = listConfigurations("(factory.instance.pid=" + instanceName + ")");

if ((configs != null) && (configs.length > 0)) {

final Semaphore sem = new Semaphore(0);

ServiceTracker<Object, Object> tracker = new ServiceTracker<Object, Object>(m_bundleContext, m_bundleContext.createFilter("(factory.instance.pid=" + instanceName + ")"), null) {

@Override

public void removedService(ServiceReference<Object> reference, Object service) {

super.removedService(reference, service);

sem.release();

}

};

tracker.open();



try {

configs[0].delete();



if (!sem.tryAcquire(1, TimeUnit.SECONDS)) {

throw new IOException("Instance did not get removed in time.");

}

}

finally {

tracker.close();

}

}

}


   Like      Feedback      java.util.concurrent.Semaphore


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Code Sample / Example / Snippet of org.apache.bcel.classfile.StackMap

    public Attribute copy( final ConstantPool _constant_pool ) {

final StackMap c = (StackMap) clone();

c.map = new StackMapEntry[map.length];

for (int i = 0; i < map.length; i++) {

c.map[i] = map[i].copy();

}

c.setConstantPool(_constant_pool);

return c;

}


   Like      Feedback      org.apache.bcel.classfile.StackMap


 Sample 36. Hibernate - Mapping the Id to RowId of Table ( workaround for Table having no primary key )

@Id
@Column(name="ROWID")
private String id;

   Like      Feedback     Hibernate  workaround for Table having no primary key  mapping Id to RowId


 Sample 37. Usage of java.util.stream.Stream

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(4, 5);

Stream.of(list1, list1)
.flatMap(list -> list.stream())
.forEach(System.out::println);

   Like      Feedback     Stream.flatMap  System.out::println


 Sample 38. Initializing a map using factory method in java 9

Usage of Map.of()

Map<String,String> countryCodeMap = Map.of("France","FR","United States","US","Canada","CA");

   Like      Feedback     java 9



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus