Java map strings to methods

Convert String to Map Java

Convert String to Map Java | As we all know the string is the collection of a sequence of characters and a Map is an interface under the collection framework which stores the elements in the key, value pair form.

The map operations can be done with a key or if you want to retrieve the value then you can use the respective key to do so. Also, the map only stores unique key values, therefore, no duplicate values are allowed on the map. Now this blog, teaches you how to convert the string to a map. The string has a particular type of elements but in the map, we need to store the elements in the form of key and value pairs. Analyzing this problem might feel difficult but this blog helps you to solve it in an easy way. In this blog, we use two methods to do so. Observe the below examples you might get more clarity.

Example:-
1. String = “Apple:1, Banana:2, Mango:3”
Map =
2. String array = < “Apple”, “Pomegranate”, “Strawberries”, “Watermelons”, “Green Grapes” >
Integer array = < 1, 2, 3, 4, 5 >
Map =
In this section, we will implement both the above methods the first method is converting a single string to the map the next one is taking two string array for key and value and then converting it to a map.

Читайте также:  Модельки awp для css

Apart from these two examples, we will also see how to convert JSON string to map using Jackson API. Example:-
Json String =
Map: .

Java Program To Convert String To Map

import java.util.HashMap; import java.util.Map; public class Main < public static void main(String[] args) < String data = "Apple:1, Banana:2, Mango:3"; Mapmap = new HashMap(); String fruits[] = data.split(","); for (String fruit : fruits) < String string1[] = fruit.split(":"); String string2 = string1[0].trim(); String string3 = string1[1].trim(); map.put(string2, string3); >System.out.println("String: " + data); System.out.println("Map: " + map); > >

String: Apple:1, Banana:2, Mango:3
Map:

In the above program to convert string to map Java, the string contains the fruit name and value which are separated by a colon (:), and each fruit is separated by a comma. Therefore first we have split based on the comma and then we have fetched the name and value. Both data had been placed on the map as key & value.

Convert String To Map Java

Now we will see an example where we have a string array and an integer array. Using these two arrays we want to create a map. In the map, we will make integer value as key and string element as value.

import java.util.HashMap; import java.util.Map; public class Main < public static void main(String[] args) < String fruits[] = < "Apple", "Pomegranate", "Strawberries", "Watermelons", "Green Grapes" >; Integer number[] = < 1, 2, 3, 4, 5 >; Map fruitMap = new HashMap(); for (int i = 0; i < fruits.length && i < number.length; i++) < fruitMap.put(number[i], fruits[i]); >System.out.println("Map: " + fruitMap); > >

Convert JSON String to Map Java

To convert JSON string to map we are going to use Jackson API. For this, we will need the following dependencies:- Jackson-core, Jackson-databind & Jackson-annotations.

Читайте также:  Custom php code in wordpress

We have the following JSON which needs to be converted into the map.

Java Program to Convert JSON String to Map using Jackson API

import java.util.HashMap; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Main < public static void main(String[] args) < String data = ""; System.out.println("String: " + data); try < HashMapmap = stringToMap(data); System.out.println("Map: " + map); > catch (JsonMappingException e) < e.printStackTrace(); >catch (JsonProcessingException e) < e.printStackTrace(); >> private static HashMap stringToMap(String data) throws JsonMappingException, JsonProcessingException < ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(data, new TypeReference()<>); > >

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

How can I map a String to a function in Java?

Couldn’t you do String to Method ? Then you can cache the methods you need to execute.

Solution 2

There aren’t any first-class standalone functions, but you can do what you want with an interface. Create an interface that represents your function. For example, you might have the following:

public interface ComputeString

Then you can create a Map object like you want in the first place. Using a map will be much faster than reflection and will also give more type-safety, so I would advise the above.

Solution 3

While you can’t have first class functions, there are anonymous classes which can be based on an interface:

interface ProcessingMethod < String method(); >Map methodMap = new HashMap(); methodMap.put("abc", new ProcessingMethod() < String method() < return "xyz" >>); methodMap.put("def", new ProcessingMethod() < String method() < return "uvw" >>); methodMap.get("abc").method(); 

Solution 4

This example uses an enum of named functions and an abstract FunctionAdapter to invoke functions with a variable number of homogeneous parameters without reflection. The lookup() function simply uses Enum.valueOf , but a Map might be worth it for a large number of functions.

Java Strings are Immutable - Here's What That Actually Means

14.10 Map Interface in Java Collection Framework

Java Map and HashMap Tutorial (Java Collections) | Key-Value Pair Entry #10.3

Java Nâng Cao 15 Map - HashMap

Map and HashMap in Java - Full Tutorial

How To Use String Methods

Java 65. Hiểu rõ cấu trúc Map của Java | Viết chương trình tra từ điển Anh - Việt

Java Examples : Convert List to Map in java with example?

Matt Ball

Comments

Currently, I have a bunch of Java classes that implement a Processor interface, meaning they all have a processRequest(String key) method. The idea is that each class has a few (say, <10) member Strings , and each of those maps to a method in that class via the processRequest method, like so:

class FooProcessor implements Processor < String key1 = "abc"; String key2 = "def"; String key3 = "ghi"; // and so on. String processRequest(String key) < String toReturn = null; if (key1.equals(key)) toReturn = method1(); else if (key2.equals(key)) toReturn = method2(); else if (key3.equals(key)) toReturn = method3(); // and so on. return toReturn; >String method1() < // do stuff >String method2() < // do other stuff >String method3() < // do other other stuff >// and so on. > 
  • My keys would have to be named the same as the method — or be named in a particular, consistent way so that it’s easy to map them to the method name.
  • This seems WAY slower than the if-else statements I have right now. Efficiency is something of a concern because these methods will tend to get called pretty frequently, and I want to minimize unnecessary overhead.

TL; DR: I’m looking for a clean, minimal-overhead way to map a String to some sort of a Function object that I can invoke and call (something like) getReturnType() on. I don’t especially mind using a 3rd-party library if it really fits my needs. I also don’t mind using reflection, though I would strongly prefer to avoid using reflection every single time I do a method lookup — maybe using some caching strategy that combines the Map with reflection.

Thoughts on a good way to get what I want? Cheers!

Couldn’t you do String to Method (java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Method.h‌​tml)? Then you can cache the methods you need to execute.

That would mean having an implementing class for every single function I want to invoke, which seems clunky and requires a bit of boilerplate for every single function. Doesn’t sound that awesome to me.

@Bears, yeah it is clunky, but you can construct anonymous classes, which should make it somewhat less clunky, like map.put(str,new ComputeString()>);

Источник

Convert String to Map Java

Convert String to Map Java | As we all know the string is the collection of a sequence of characters and a Map is an interface under the collection framework which stores the elements in the key, value pair form.

The map operations can be done with a key or if you want to retrieve the value then you can use the respective key to do so. Also, the map only stores unique key values, therefore, no duplicate values are allowed on the map. Now this blog, teaches you how to convert the string to a map. The string has a particular type of elements but in the map, we need to store the elements in the form of key and value pairs. Analyzing this problem might feel difficult but this blog helps you to solve it in an easy way. In this blog, we use two methods to do so. Observe the below examples you might get more clarity.

Example:-
1. String = “Apple:1, Banana:2, Mango:3”
Map =
2. String array = < “Apple”, “Pomegranate”, “Strawberries”, “Watermelons”, “Green Grapes” >
Integer array = < 1, 2, 3, 4, 5 >
Map =
In this section, we will implement both the above methods the first method is converting a single string to the map the next one is taking two string array for key and value and then converting it to a map.

Apart from these two examples, we will also see how to convert JSON string to map using Jackson API. Example:-
Json String =
Map: .

Java Program To Convert String To Map

import java.util.HashMap; import java.util.Map; public class Main < public static void main(String[] args) < String data = "Apple:1, Banana:2, Mango:3"; Mapmap = new HashMap(); String fruits[] = data.split(","); for (String fruit : fruits) < String string1[] = fruit.split(":"); String string2 = string1[0].trim(); String string3 = string1[1].trim(); map.put(string2, string3); >System.out.println("String: " + data); System.out.println("Map: " + map); > >

String: Apple:1, Banana:2, Mango:3
Map:

In the above program to convert string to map Java, the string contains the fruit name and value which are separated by a colon (:), and each fruit is separated by a comma. Therefore first we have split based on the comma and then we have fetched the name and value. Both data had been placed on the map as key & value.

Convert String To Map Java

Now we will see an example where we have a string array and an integer array. Using these two arrays we want to create a map. In the map, we will make integer value as key and string element as value.

import java.util.HashMap; import java.util.Map; public class Main < public static void main(String[] args) < String fruits[] = < "Apple", "Pomegranate", "Strawberries", "Watermelons", "Green Grapes" >; Integer number[] = < 1, 2, 3, 4, 5 >; Map fruitMap = new HashMap(); for (int i = 0; i < fruits.length && i < number.length; i++) < fruitMap.put(number[i], fruits[i]); >System.out.println("Map: " + fruitMap); > >

Convert JSON String to Map Java

To convert JSON string to map we are going to use Jackson API. For this, we will need the following dependencies:- Jackson-core, Jackson-databind & Jackson-annotations.

We have the following JSON which needs to be converted into the map.

Java Program to Convert JSON String to Map using Jackson API

import java.util.HashMap; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Main < public static void main(String[] args) < String data = ""; System.out.println("String: " + data); try < HashMapmap = stringToMap(data); System.out.println("Map: " + map); > catch (JsonMappingException e) < e.printStackTrace(); >catch (JsonProcessingException e) < e.printStackTrace(); >> private static HashMap stringToMap(String data) throws JsonMappingException, JsonProcessingException < ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(data, new TypeReference()<>); > >

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

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