Try to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray json = (JSONArray) map;
for (int i=0; i < json.length(); i++) {
JSONObject e = json.get(i);
System.out.println(e);
}
}
Answer from vijay on Stack OverflowTry to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray json = (JSONArray) map;
for (int i=0; i < json.length(); i++) {
JSONObject e = json.get(i);
System.out.println(e);
}
}
You are casting it wrong.
JSONObject json = (JSONObject) map;
This casting is wrong (JSONObject) map. it should be (JSONArray) map.
Next time before casing object, you perhaps want to check type of object like this.
System.out.println(map.getClass().getName());
So, you want to return the indexes of first occurrences of distinct items?
Maps can be really cool for these things, and in this case, all you want to actually remember is when was the first occurrence of each distinct element.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DistinctValues {
public static List<Integer> distinctIndexes(String[] strings) {
// holds the mapping { string => index of first occurence of that string }
Map<String, Integer> firstOccurenceMap = new HashMap<String, Integer>();
// do a scan through all the items
for (int i = 0; i < strings.length; i++) {
// store the index position of a string only if you haven't encountered it before
firstOccurenceMap.putIfAbsent(strings[i], i);
}
return new ArrayList<Integer>(firstOccurenceMap.values());
}
public static void main(String[] args) {
String[] strings = new String[] { "1", "1", "3", "3", "3", "3", "3", "3" };
System.out.println(distinctIndexes(strings));
}
}
The output:
[0, 2]
This is a simple way of doing it:
String[] temp2 = new String[]{"1", "1", "3", "1", "3" };
List<String> values = new ArrayList<>();
List<Integer> indices = new ArrayList<>();
for( int i = 0; i < temp2.length; ++i ){
String s = temp2[i];
if( ! values.contains( s ) ){
values.add( s );
indices.add( i );
}
}
You can now create arrays from the Lists:
String[] uniq = values.toArray(new String[values.size()]);
Integer[] inds = indices.toArray(new Integer[indices.size()]);
Java doesn't support associative arrays, however this could easily be achieved using a Map. E.g.,
Map<String, String> map = new HashMap<String, String>();
map.put("name", "demo");
map.put("fname", "fdemo");
// etc
map.get("name"); // returns "demo"
Even more accurate to your example (since you can replace String with any object that meet your needs) would be to declare:
List<Map<String, String>> data = new ArrayList<>();
data.add(0, map);
data.get(0).get("name");
See the official documentation for more information
Java doesn't have associative arrays like PHP does.
There are various solutions for what you are doing, such as using a Map, but it depends on how you want to look up the information. You can easily write a class that holds all your information and store instances of them in an ArrayList.
public class Foo{
public String name, fname;
public Foo(String name, String fname){
this.name = name;
this.fname = fname;
}
}
And then...
List<Foo> foos = new ArrayList<Foo>();
foos.add(new Foo("demo","fdemo"));
foos.add(new Foo("test","fname"));
So you can access them like...
foos.get(0).name;
=> "demo"
var value = state[country[0][0]] [i][1];
There are a couple or three errors in your code. Assuming country has a list of countries and state keeps the states of the country...
country = ["USA"];
state = {"USA": [["NewYork","NY"],["Ohio","Oh"]] };
for (var i = 0; i < state[country[0]].length; i++) {
var key = state[country[0]] [i][0];
var value = state[country[0]] [i][1];
}
If your data structure has many-to-one mapping between keys and values you should iterate over entries and pick all suitable keys:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
In case of one-to-one relationship, you can return the first matched key:
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
In Java 8:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
Also, for Guava users, BiMap may be useful. For example:
BiMap<Token, Character> tokenToChar =
ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease.
The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.
There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidi maps.
If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.
Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.
Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.
Since version 4.0 the official Apache Commons Collections™ library supports generics.
See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.
assuming when you say key you mean value (as in values in an array),
final String PREFIX = "yourPrefix";
for(String value : valueList) {
if(value.startwith(PREFIX)) {
<do whatever...>
}
here is the link to the java Doc http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)
I am assuming you are scanning the config file for Strings that have similar prefixes. Why not try scanning them in grouped instead of scanning them in all in one hashmap. If you know already the specified prefixes try creating an arraylist for each prefix and while scanning receive the given prefix and add it accordingly.
StringTokenizer s = new StringTokenizer ("Configuration File : Server_intenties = keyId_11503, keyId_11903 : Server_passcodes = keyCode_1678, keyCode_9893", " ");
ArrayList<String> keyCode = new ArrayList();
ArrayList<String> keyId = new ArrayList();
while(s.hasMoreTokens){
String key = s.nextToken
if(key.contains("keyId")){
keyId.add(key);
}
if(key.contains("keyCode")){
keyCode.add(key);
}
}
System.out.println(keyCode);
System.out.println(keyId);
I mean you could achieve it that way, but it is much less efficient. Searching an array for a specific value will be of O(n) complexity while hashmaps only take O(1) in the best case scenario (with no chaining).
It's not possible. Arrays are Integer Index based in Java.
HashMap is specifically designed for that purpose.