How can I fix this:
class Name {
public void createArray(String name)
{
String name=new String[200];//we know, we can't do this- duplicate local variable,need a fix here.
}
}
I want to create array of strings with name of array as input parameter = name,
Example:
1) for function call createArray(domain1) -> I need essentially this to happen-> String domain1=new String[200];
2)for function call createArray(domain22)-> I need function to create String domain22=new String[200];
Hope this edit helps.
NOTE: There is a possibility that same name is passed byfunction twice/thrice. like createArray(domain1);, at that point of time I want to ignore the creation of array.
Store your new String[200] objects in a Map keyed by the name
Map<String, String[]> myarrays = new HashMap<String, String[]>();
myarrays.put("name", createArray("name"));
myarrays.put("test", createAray("test"));
then when you want one of them do
String[] data = myarrays.get("test");
Related
Is there a way to get or set an array element stored in a Java Map?
Example:
If we have a map like this:
{
name: "Blah",
friends: ["Foo", "Bar"]
}
Map<String, Object> myMap = new HashMap<>();
List<String> friends = new ArrayList<>();
myMap.put("name", "Blah");
myMap.put("friends", friends);
Is it possible to use Reflection to get or set the first element in the friends array in the "myMap" from the string: "myMap.friends[0]"
Your question is not very clearly written and I believe that's why you are not getting the answer you expect but, If I understood your question correctly, you need to parse the following input string at runtime that you don't know beforehand:
myMap.friends[0]
And this should be parsed into components like:
mapName = "myMap"
mapKey = "friends"
valueIndex = 0
And with this information, you need to manipulate data in a Map at runtime through reflection.
Note: This only makes sense if you could potentially have more complex expressions, using different sort of objects and accessing nested properties of retrieved objects, otherwise you wouldn't need reflection at all.
Note 2: You may want to have a look at JXPath which already does a lot of this for you based on a XPath-like syntax for navigating object graphs.
That said, if my assumptions are correct and you still want to do it yourself, consider the following example.
For the sake of demonstration, let's consider our map is returned by a method myMap inside a Context.
private static class Context {
public Map<String, Object> myMap() {
Map<String, Object> myMap = new HashMap<>();
List<String> friends = new ArrayList<>();
friends.add("Foo");
friends.add("Bar");
myMap.put("name", "Blah");
myMap.put("friends", friends);
return myMap;
}
}
I'm assuming you are already parsing the input string into the different components. If not, for this simple string you could do it with simple regular expressions. If you already have the components, let's consider the following method:
public static Object readContextMap(Context context,
String mapName, String mapKey, Integer mapValueIndex) throws Exception {
// gets Context class for inspection
Class<?> cls = context.getClass();
// search for a method based on supplied mapName
Method mapMethod = cls.getDeclaredMethod(mapName);
// get a value from the retrieved map based on mapKey
Object mapValue = mapMethod.getReturnType()
.getDeclaredMethod("get", Object.class)
.invoke(mapMethod.invoke(context), mapKey);
// if the result is of type list, use the index to return the indexed element
if (List.class.isAssignableFrom(mapValue.getClass())) {
return ((List<?>)mapValue).get(mapValueIndex);
}
// otherwise return the object itself
return mapValue;
}
For testing purposes, consider the following main method:
public static void main(String[] args) throws Exception {
Context context = new Context();
String input = "myMap.friends[0]";
// parse input into...
String mapName = "myMap";
String mapKey = "friends";
Integer valueIndex = 0;
Object firstFriend = readContextMap(context, mapName, mapKey, valueIndex);
System.out.println(firstFriend);
// prints Foo
Object name = readContextMap(context, "myMap", "name", null);
System.out.println(name);
// prints Blah
}
This should be approximately what you want. You can easily create variations of this to set values as well. Please bear in mind that this code is just for demo purposes and needs a better error handling (e.g. verify if the context is really returning a map and nothing else).
This should be something along the lines you are looking for.
There's no need to use reflection here. You can simply cast it (which is also unsafe, but less so).
You can just do this:
List<String> friends = (List<String>) myMap.get("friends");
friends.set(0, "Bob");
I have a huge group of keys like more than 10L like the below in csv file
ABA,100
ABC,200
ABCs,50
ABM,65
ABMs,86
ABS,86
AC,54
ACLU,123
ACT,56
ACTH,154
AD,644
ADC,76
ADD,10.
Do I need to create the user define an object for the above key pairs? Will it create any memoery problem for creating more than 10L user define object?
My input String looks like [ABS,AC,ACLU,ABC]
I want the output AC,ABS,ACLU,ABC based on the count.
How to achieve it in easier way of Java 1.8.
Thanks.
You could add each line of your csv to a List<String> myList
Then, you will have to create a custom Comparator in order to sort your list based on the value, so something like the following,
private void customSorting(List<String> myList) {
Collections.sort(myList, (String s1, String s2) -> {
String valuePart1 = s1.split(",")[1];
String valuePart2 = s2.split(",")[1];
return Integer.valueOf(valuePart1).compareTo(Integer.valueOf(valuePart2));
});
}
Finally, just call your method like customSorting(myList); in any place of your code you need it
Of course, you have to modify the sorted list as well to keep only the first part (before comma) for each String value but that's easy.
An alternative could also be to create a class like the following,
public class MyClass {
private String key;
private String value;
// All the getters, setters, constructors, etc
}
, and then read each line of your csv, create an equivalent MyClass POJO and add it to a List<MyClass> myList.
You have to write your own custom Comparator again for List<MyClass> in a similar way like I did for the List<String>,
private void customSorting(List<MyClass> myList) {
Collections.sort(myList, (MyClass a, MyClass b) -> {
return Integer.valueOf(a.getValue()).compareTo(Integer.valueOf(b.getValue()));
});
}
Finally, create a new list from the sorted one by keeping only the keys
// Facility table attributes to be read in json format
String facilityName[], recApp[], recFacility[], sendApp[],
sendFacility[], enable[], doneness[], retryLimit[],
watchDelay[], retryDelay[], ackTimeout[],
keepConOpen[], sendTimeout[], cleanupDelay[],
host[], port[];
String facilityTableAttrs[][] = new String[][] {
facilityName, recApp, recFacility, sendApp,
sendFacility, enable, doneness, retryLimit,
watchDelay, retryDelay, ackTimeout, keepConOpen,
sendTimeout, cleanupDelay, host, port};
I have array of arrays called facilityTableAttrs declared as above.
I have 2 questions:
1) Is it possible to do the above array declaration in a single step ?
2) I wish to get the individual array names of these 1D array using something like:
for(i = 0; i < facilityTableAttrs.length; i++) {
System.out.println(facilityTableAttrs[i].toString());
}
but it fails. How to get the individual array names as string?
The first list of arrays you declare don't seem to be initialized anywhere.
As such they are null, and invoking toString on any of them will cause a NullPointerException to be thrown, hence "it fails".
By the way, invoking toString on an non-null array would actually print something similar to the Object.toString representation, which is not what you want (Arrays.toString(myArray) is your friend here).
You could initialize each and every single array and populate them optionally, before adding them to the main String[][] but I recommend you don't.
Instead, investigate the collections framework.
What you could use here is a Map<String, List<String>>.
Or better even, a custom object with properties such as List<String> facilityName, List<String> recApp, etc.
Finally, note the variable naming, which is camelBack according to code conventions.
This is not possible with arrays. You need to use map, like so:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
You need to choose correct data structure for your problem.
Arrays are used only for storing values, thay are not interestd in bounding names to them.
Maps on the other hands are great with bounding names (keys that are unique) to any type of value.
I propose to use a wrapper class:
public class Facility {
private final String name;
private final List<String> values;
public Facility(String name) {
this.name = name;
this.values = new ArrayList<>();
}
public String getName() {
return name;
}
public List<String> getValues() {
return values;
}
}
and then do:
Facility[] facilities = new Facility[] {
new Facility("facility 1"),
new Facility("facility 2"),
new Facility("facility 3"),
new Facility("facility 4"),
};
for(Facility facility : facilities) {
System.out.println(facility.getName());
}
To add a value to a facility you'd do:
Facility facility = facilities.get(0);
facility.getValues().add("bla");
If you need to look up facilities by name, then use a Map instead of an array:
...
// see createLookup method below
Map<String, Facility> facilities = createLookup(
new Facility("facility 1"),
new Facility("facility 2"),
new Facility("facility 3"),
new Facility("facility 4"));
// print names
for(Facility facility : facilities.values()) {
System.out.println(facility.getName());
}
// add a value
Facility facility = facilities.get("facility 3");
facility.getValues().add("bla");
}
private Map<String, Facility> createLookup(Facility.. facilities) {
// use TreeMap to have sorted keys
Map<String, Facility> lookup = new TreeMap<>();
for(Facility facility : facilities) {
lookup.put(facility.getName(), facility);
}
return lookup;
}
I have managed to fetch a string from the database and be able to store some of its elements in variable so as to reduce the number of times the app interacts with the databse. However I wanted the first element to be fetched from the database to be stored in a list but it keeps generating an error when i parse the string to a new list. please help
//String fetched from the database
final String[] rec = split(myresult,seperator);
//loc is the first String to be parsed to a String..
//desc is the 2nd string to be parsed to a textarea
//coords 3rd string which contains coordinates..
String loc=rec[0];
final String desc=rec[1];
String coords=rec[2];
//ERROR IS GENERATED HERE!!!
listmboya=new List(loc);
//Separate the coordinates in the string...
String seperator2=",";
String [] coordinates=split(coords,seperator2);
String lat=coordinates[0];
String lot=coordinates[1];
//convert them to floats..
item1=Float.parseFloat(lat);
item2=Float.parseFloat(lot);
list is an iterface,
try
listmboya=new ArrayList();
listmboya.add(loc);
You cannot instantiate List object. Its an interface and not a class. You need an ArrayList which is the implementing class of List and also, there is no constructor for ArrayList that takes String as parameter.
So, you need to create an ArrayList<String> and then add your String to it.
So you need to do it like this: -
List<String> listmboya=new ArrayList<String>();
listmboya.add(loc);
Make sure to declare your listmboya as List<String>
UPDATE: - Post some more Code in case this doesn't work. We need to look at more of them.
List is the abstract class, can not be instantiated.
just try like this:
listmboya = new ArrayList<String>();
listmboya.add(loc);
Let's say I have an instantiated object:
private static ArrayList<Boolean> P1SOLUTION = new ArrayList<Boolean>();
There will be similar objects such as P2SOLUTION, P3SOLUTION, etc.
I want the functionality of:
Arrays.toString(P1SOLUTION);
(Which prints the array as a string).
But let's say all I have is...
String myString = "P1" + "SOLUTION";
So, when I invalidly write:
Arrays.toString(myString);
I really want the String myString to reference the object P1SOLUTION in this example. How can I create this functionality?
Store your object instances in a Map. Then reference the instances by name:
Something like this:
Map myMap = new HashMap();
myMap.put("P1SOLUTION", new ArrayList<Boolean>());
Then get your instance:
String myString = "P1" + "SOLUTION";
List myList = myMap.get(myString);
Hope this will help you.