How to put java

Java HashMap put()

Note: If key is previously associated with a null value, then also the method returns null .

Example 1: Java HashMap put()

import java.util.HashMap; class Main < public static void main(String[] args) < // create an HashMap HashMaplanguages = new HashMap<>(); // insert items to the HashMap languages.put("Java", 14); languages.put("Python", 3); languages.put("JavaScript", 1); // display the HashMap System.out.println("Programming Languages: " + languages); > >

In the above example, we have created a HashMap named languages . Here, the put() method inserts the key/value mappings to the hashmap.

Note: Every item is inserted in random positions in the HashMap .

Example 2: Insert Item with Duplicate Key

import java.util.HashMap; class Main < public static void main(String[] args) < // create an HashMap HashMapcountries = new HashMap<>(); // insert items to the HashMap countries.put("Washington", "America"); countries.put("Ottawa", "Canada"); countries.put("Kathmandu", "Nepal"); System.out.println("Countries: " + countries); // add element with duplicate key String value = countries.put("Washington", "USA"); System.out.println("Updated Countries: " + countries); // display the replaced value System.out.println("Replaced Value: " + value); > >
Countries: Updated Countries: Replaced Value: America

In the above example, we have used the put() method to insert items to the hashmap. Notice the line,

countries.put("Washington", "USA");

Here, the key Washington is already present in the hashmap. Hence, the put() method replaces the previous value America with the new value USA .

Читайте также:  Checked javascript type text

Note: Till now, we have only added a single item. However, we can also add multiple items from Map to a hashmap using the Java HashMap putAll() method.

Источник

How to Execute an HTTP PUT Request in Java

In this tutorial, you will learn how to execute an HTTP PUT request in Java. You might also be interested to learn how to execute other HTTP methods. If you are, then please check the following tutorials as well:

The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload. This method is Idempotent, which means that executing it should not have any side effects.

To execute an HTTP request in Java, we need to have an HTTP client as a dependency. In this tutorial, we will cover the HTTP PUT Request using the Apache HttpClient.

First, we need to add Maven dependency:

 org.apache.httpcomponents httpclient 4.5.13  

Find other versions here → Apache HTTP Client. If you are not using Maven, you can also download JAR from the location above.

Execute an HTTP PUT request in Java using Apache HTTP client

Below is a simple example of executing an HTTP PUT request in Java.

import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class Test < public static void main(String[] args) throws IOException < try (CloseableHttpClient httpclient = HttpClients.createDefault()) < HttpPut httpPut = new HttpPut("https://jsonplaceholder.typicode.com/posts/1"); // specify the PUT body to send to the server as part of the request httpPut.setEntity(new StringEntity("")); System.out.println("Executing PUT request. "); HttpResponse response = httpclient.execute(httpPut); System.out.println("Status code:" + response.getStatusLine().getStatusCode()); String responseBody = new BasicResponseHandler().handleResponse(response); System.out.println(responseBody); > > >

Here we used the try-with-resources to create an HttpClient. That means we don’t have to close it after executing the request. The try-with-resources statement ensures that each resource is closed at the end of the statement.

We also used the BasicResponseHandler to retrive the response body and response.getStatusLine().getStatusCode() to retrive the response status code.

Execute an HTTP PUT request with headers

We can also add HTTP headers to the request, like in the following example:

import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class Test < public static void main(String[] args) throws IOException < try (CloseableHttpClient httpclient = HttpClients.createDefault()) < HttpUriRequest request = RequestBuilder.put() .setUri("https://jsonplaceholder.typicode.com/posts/1") .setHeader(HttpHeaders.CONTENT_TYPE, "application/json") .setHeader("Authorization", "Bearer 123token") // add request body .setEntity(new StringEntity("")) .build(); System.out.println("Executing PUT request. "); HttpResponse response = httpclient.execute(request); System.out.println("Status code: " + response.getStatusLine().getStatusCode()); String responseString = new BasicResponseHandler().handleResponse(response); System.out.println("Response: " + responseString); > > >

We used the RequestBuilder class to build the request with all the required data (URL, headers, request body).

Источник

How to add an object in HashMap by HashMap put() method

You have read the HashMap in Java and now we will see how to insert objects in HashMap. The HashMap class provides some methods like Java HashMap put() method, putAll() method(java map put all). Here we will discuss HashMap put example.

Here is the table content of the article will we will cover this topic.
1. put(K key, V value) method
2. putAll(Map map) method
3. putIfAbsent(K key, V value) method

put(K key, V value) method

This method is used to set the value with the corresponding key in HashMap. It inserts the entry(Key-Value) in the hashmap. If the HashMap already contained the key, then the old value is replaced by a new Value.
It returns null if there is no value presented in the hashmap for the given key. But it returns the old object if there is any value presented with the given key.

java hashmap put

Where K is the key with which the specified value(V) is to be associated in HashMap.
V is the value to be associated with the specified key(K) in HashMap.
return NULL, if there was no mapping for key. It returns the previous value if the associated key already present.

import java.util.HashMap; public class ExampleOfHashMap < public static void main(String[] args) < HashMaphashMap = new HashMap(); // Adding element in HashMap // The put method returns the old object after performing insertion // It will return null if there is no mapping for the given key String previousObject = hashMap.put(1, "JavaGoal"); System.out.println("Previous object: "+ previousObject); // It will return the previous object and replace with a new object for given key previousObject = hashMap.put(1, "JavaGoal.com"); System.out.println("Previous object: "+ previousObject); hashMap.put(2, "Learning"); hashMap.put(3, "Website"); System.out.println("All Pair of HashMap: "+hashMap); > >

Output: Previous object: null
Previous object: JavaGoal
All Pair of HashMap:

putAll(Map map) method

This method is used to copy all elements of the specified map in the current HashMap. It copies all the mapping(Key and value pairs) of the specified Map to the current HashMap. It returns NullPointerException if the given map is null.

java hashmap put

Where, map is specified Map which you want to copy.
return Void, it doesn’t return anything.

import java.util.HashMap; public class ExampleOfHashMap < public static void main(String[] args) < HashMaphashMap = new HashMap(); hashMap.put(1, "JavaGoal.com"); hashMap.put(2, "Learning"); hashMap.put(3, "Website"); HashMap newHashMap = new HashMap(); newHashMap.putAll(hashMap); System.out.println("All Pair of HashMap: "+newHashMap); > >

Output: All Pair of HashMap:

putIfAbsent(K key, V value) method

This method is used to put the given value with the corresponding key in HashMap. If the specified key is not already present in HashMap. It works similarly like put() method except the if condition.

java hashmap put

Where K is the key with which the specified value(V) is to be associated with HashMap.
V is the value to be associated with the specified key(K) in HashMap.
return NULL, if there was no mapping for key. It returns the previous value if the associated key already present.

import java.util.HashMap; public class ExampleOfHashMap < public static void main(String[] args) < HashMaphashMap = new HashMap(); // Adding element in HashMap String previousObject = hashMap.putIfAbsent(1, "JavaGoal.com"); System.out.println("Previous object: "+ previousObject); hashMap.put(2, "Learning"); hashMap.put(3, "Website"); System.out.println("All Pair of HashMap: "+hashMap); > >

Output: Previous object: null
All Pair of HashMap:

Leave a Comment Cancel reply

You must be logged in to post a comment.

  • Basics Of Java
    • What is JAVA language
    • JAVA features/advantage
    • How to run Java program
    • Difference between JRE, JDK and JVM
    • Java Virtual Machine(JVM) & JVM Architecture
    • Variables in Java
      • Local Variable Type Inference (Java var)
      • Java control statements
        • if statement in Java
        • Switch statement Java
        • class and object in Java
        • Constructor Overloading in Java
        • Constructor chaining in java
        • Multiple inheritance using interface in java
        • Method overloading in Java
        • Method overriding in Java
        • Abstract class in java
        • Interface in java
          • Multiple inheritance using interface in java
          • Java import package
          • final variable in Java
          • final method in java
          • final class in Java
          • Static variable in java
          • Static method in java
          • Static block in java
          • Static class in java
          • Thread life cycle in java
          • Thread scheduler in java
          • Java Thread Sleep
          • join() method in java
          • yield() method in java
          • wait() method in Java
          • notify() method in Java
          • Thread class in java
          • Daemon thread in java
          • Callable and Future in java
          • What is immutable String in java
          • What is a mutable string
          • String concatenation
          • String comparison in Java
          • Substring in Java
          • Convert string to int
          • String Replace in Java
          • Substring in Java
          • String constructor in java
          • string methods in java
          • try and catch java block
          • finally block in java
          • throw and throws keyword in java
          • Chained exception in java
          • User defined exception in java
          • Java try with resource
          • ArrayList in java
            • Java ArrayList methods
            • How to add the element in ArrayList
            • How to replace element in an ArrayList?
            • How to remove element from arraylist java
            • How to access ArrayList in java
            • How to get index of object in arraylist java
            • How to Iterate list in java
            • How to achieve Java sort ArrayList
            • How to get java sublist from ArrayList
            • How to Convert list to array in java
            • How to convert array to list java
            • How to remove duplicates from ArrayList in java
            • Difference between ArrayList and array
            • Difference between ArrayList and LinkedList
            • Java linked list methods
            • How to do LinkedList insertion?
            • How to perform deletion in linked list
            • How to get the element from LinkedList
            • Traverse a linked list java
            • Searching in linked list
            • How to convert linked list to array in java
            • How to remove duplicates from linked list
            • How to perform linked list sorting
            • Difference between ArrayList and LinkedList
            • How to add element in HashSet?
            • How to remove elements from HashSet?
            • TreeSet internal working
            • TreeSet Methods in Java
            • Internal working of HashMap
            • HashMap method in java
            • How to add an object in HashMap by HashMap put() method
            • How to get values from hashmap in java example
            • How to remove the element by Java HashMap remove() method
            • How to replace the value by HashMap replace() method
            • How to check the map contains key by hashmap containskey() method
            • How to get java map keyset by hashmap keyset() method
            • How to get java map entryset by java entryset() method
            • How to iterate hashmap in java
            • TreeMap(Comparator comp)
            • Treemap methods
            • Generic types in Java
            • Advantages of generics in java
            • toString() method in Java
            • equals() method in java
            • Java hashCode() method
            • clone() method in java
            • finalize() method in java
            • getclass() method in java
            • wait() method in Java
            • notify() method in Java
            • Garbage collector in java
            • finalize() method in java
            • equals() method in java
            • Java hashCode() method
            • Comparable java interface
            • Comparator interface
            • Difference between comparable and comparator
            • Why Comparable and Comparator are useful?
            • comparator() method in java
            • functional interface in java 8
            • Predicate in java 8
              • Why predicate in java 8
              • Why consumer in java 8
              • How lambda expression works in java
              • Java 8 lambda expression example
              • Why Lambda expression use functional interface only
              • Lambda expression with the return statement
              • Java stream operations in java
              • Intermediate operation in Java 8
              • Terminal operations in java 8
              • Short circuit operations in Java 8
              • Lazy evaluation of stream
              • Converting stream to collections and Arrays
              • Java 9 module
              • try with resource improvement
              • Optional Class Improvements
              • Private methods in interface
              • Factory Methods for Immutable List, Set, Map and Map.Entry
              • Jshell java 9
              • Java CompletableFuture API Improvements
              • Local Variable Type Inference (Java var)
              • Java 11 String New Methods

              Content copy is strictly prohibited. Copyright © by JavaGoal 2022. Designed & Developed By Finalrope Soft Solutions Pvt. Ltd.

              Источник

Оцените статью