Howto check if a TreeMap contains a specific object? - java

In an application I have this TreeMap object:
treePath = new TreeMap<String, DLFolder>();
The first String parameter should be the key and the DLFolder is the value.
Ok the DLFolder object have this method dlFolder.getPath() that return a String
So I want to know if the treePath object contains a DLFolder object having a specific path value
Can I do this thing?
Tnx

for (DLFolder dlf : treePath.values()) {
if ("A SPECIFIC PATH".equals(dlf.getPath()) {
// do someting with the dlf
}

In Java 8 this is rather straightforward.
treePath.values().anyMatch(dlf -> dlf.getPath().equals(specificValue))

You can loop through the values of the TreeMap:
for (DLFoder folder : treePath.values())
if (folder.getPath().equals(somePathValue))
// path found!

If the map's key is also the value stored in dlFolder.getPath(), then yes, you can just call treePath.contains("Value");.
Other options include:
Iterating over treePath's values either using an iterator, an enhanced for loop, or the Java 8 streams.
Creating another map to map the same DLFolder objects, but by path.

Related

How to use contains() with substring

i have an ArryList which have (name+"\n"+phoneNumber) so I wanna see if the name is containing with the list ? I used this code
HashSet<String> set = new HashSet<String>(ContactsList);
if (set.contains(name))
{}
else
{
ContactsList.add(name+"\n"+phoneNumber+"\n");
}
but how to use substring in contains so I get just the name from it to contain it with the name that I wanna add it to the list
and thanks
Don't add the data in ArrayList as (name+"\n"+phoneNumber),
Create a class which 2 attributes name and phoneNumber, then create object of that class set both attributes and add that object in the ArrayList.
This is the right way of doing it and your problem also will be solved.

How to maintain JSON's order in Groovy's JsonSlurper?

I am reading a simple JSON....
{"A":0,"B":0,"C":2,"D":0,"F":5}
into a map using JsonSlurper in Groovy...
Map gradeDistributon = jsonSlurper.parseText(jsonString)
But when iterating over this map with a closure..
gradeDistributon.each{ entry ->
println "From map got key ${entry.key}"
I am seeing the keys are not in the order they were in the original JSON, for example 'C' comes first. I think this is because Map does not maintain insertion order in Java. Is there a way I can keep the order of the original JSON?
If it means reading the JSON in a different way (instead of into a Map with JsonSlurper) then I am fine with that if you can show me how.
You can set JVM system property jdk.map.althashing.threshold to make JsonSlurper to use a LinkedHashMap instead of TreeMap as the internal Map implementation, e.g. -Djdk.map.althashing.threshold=512.
The reason is in source code of groovy.json.internal.LazyMap used by JsonSlurper.
private static final String JDK_MAP_ALTHASHING_SYSPROP = System.getProperty("jdk.map.althashing.threshold");
private void buildIfNeeded() {
if (map == null) {
/** added to avoid hash collision attack. */
if (Sys.is1_7OrLater() && JDK_MAP_ALTHASHING_SYSPROP != null) {
map = new LinkedHashMap<String, Object>(size, 0.01f);
} else {
map = new TreeMap<String, Object>();
}
}
}
Please note this solution should be used as a hack as it depends on Groovy's internal implementation details. So this behavior may change in future version of Groovy.
See my blog post for details.
So it was just a matter of sorting the keys after JsonSlurper built the Map, for that I just read into a TreeMap which sorts the keys by default..
TreeMap gradeDistributon = jsonSlurper.parseText(jsonString)
I can't reproduce your behaviour with groovy 2.4.5 but you can try using LinkedHashMap (allow to iterate over map keys maintaining the order in which the entries were inserted):
import groovy.json.*
def jsonText = '''
{"A":0,"B":0,"C":2,"D":0,"F":5,"G":7,"H":9}
'''
LinkedHashMap json = new JsonSlurper().parseText(jsonText)
json.each{ entry ->
println "${entry.key}"
}
NOTE: as stated by #XenoN the JsonSlurper() sort the json keys during the parsing process so independently of the input order (ie. {"H":0,"B":0,"A":2,"D":0,"G":5,"F":7,"C":9}) the output of JsonSlurper will be always: {"A":2,"B":0,"C":9,"D":0,"F":7,"G":5,"H":0}.
Using the LinkedHashMap instead of a HashMap we preserve the order given by JsonSlurper.
I run the same code on Groovy 2.4.x and on 3.0.x.
On 2.4 the order is preserved,but on 3.0 is sorted asc by default.
use the JsonSluperClassic().parse() instead it will preserve the order

lambda foreach add to map not working

I got the following variables
List<Pruefvorschrift> listP = new ArrayList<Pruefvorschrift>();
ObservableMap<TestDevice,List<Pruefvorschrift>> testDev = FXCollections.emptyObservableMap();
in one function i want to fill the testDev by using lambda expression
//first call REST service and get data
List<TestDevice> test_dev = call.getTestDevice("");
//now do a foreach to add each entry (as key) to the testDev ObservableMap with a empty List (as value)
test_dev.stream().forEach(td ->{
TestDevice t = td;
testDev.put(t, listP);
});
but all i get is a error
java.lang.UnsupportedOperationException at
java.util.AbstractMap.put(AbstractMap.java:209)
which obviously is this row
testDev.put(t, listP);
maybe i misunderstood the new stream api but i only want to fill the observable map with all the result of the call (key) and an empty List (value which will be modified later).
Any help? Thx
Whatever Map type is returned by FXCollections#emptyObservableMap
FXCollections.emptyObservableMap();
does not support the put method. You can't add anything to it. As the javadoc states
Creates and[sic] empty unmodifiable observable list.
This has nothing to do with lambda expressions or the Stream api.
just to complete here (Sotirios Delimanolis was absolute right and me so wrong :). My problem was solved by doing a correct job with the map itself
//create empty map
Map<TestDevice,List<Pruefvorschrift>> map = new HashMap<TestDevice,List<Pruefvorschrift>>();
//use this map to create the ObservableMap
ObservableMap<TestDevice,List<Pruefvorschrift>> testDev = FXCollections.observableMap(map);
And all works...Thx Sotirios

Java : List of Maps when type of values is ArrayList

I'm working on a java project and i want to create a list of Maps that the type of keys is Character and the values are ArrayLists of Characters. I have written something like this :
List<Map<Character, ArrayList<Character>>>
but the eclipse says : Syntax error on token ">>>", VariableDeclarator expected after this token
How can i do it ? any idea ?
The compiler is expecting a variable name to comply with Java syntax:
List<Map<Character, List<Character>>> myList =
new ArrayList<Map<Character, List<Character>>>();
List<Map<Character, ArrayList<Character>>> list ; should be given
see the screen shot below
You can declare a variable as an interface (e.g. List) but to create an instance, you must choose an implementation (e.g. ArrayList):
List<Map<Character, ArrayList<Character>>> myList = new ArrayList<Map<Character, ArrayList<Character>>>();

how to make key of map to variable name

In java,i have a Map that contains certain values. I want to create a String variable that having the name of the key of the map. How it is possible in java?
Map<String,String> values=new HashMap<String, String>();
values.put("dataSource", "bloomberg");
values.put("dataProvider", "bloomberg");
values.put("observationTime", "close");
this is the map. And i want to make the variables with values :
String dataSource="bloomberg";
String dataProvider="bloomberg";
String observationTime="close";
How it is possible in java?
Java doesn't support dynamic variable names. All the variables have to be present at compile time (this means that only the containers would be made at compile time) and at runtime, values are simply assigned and changed according to the logic of the program.
A few languages support creating variables with dynamic names, but it is not possible in Java
Try this
String dataSourceKey = "dataSource";
String dataSourceValue = "bloomberg";
values.put(dataSourceKey, dataSourceValue);
Now, when reading the values from the map
String dataSource = values.get(dataSourceKey);
Hope this helps

Categories

Resources