0

I have the following HashMap data printing only the keySet(): -

[P001, P003, P005, P007, P004, P034, P093, P054, P006]

And the following ArrayList data as an output: -

[P001]
[P007]
[P034]
[P054]

This is how it is getting printed for both of them. I want to compare the array list data with the hash map data one by one. So, that the value [P001] should present inside HashMap.

Here is the part of code I have tried:-

def count = inputJSON.hotelCode.size() // Where "hotelCode" is particular node in inputJSON

Map<String,List> responseMap = new HashMap<String, List>()
for(int i=0; i<count; i++) {
    Map jsonResult = (Map) inputJSON
    List hotelC = jsonResult.get("hotelCode")
    String id = hotelC[i].get("id")
    responseMap.put(id, hotelC[i])
}

String hotelCFromInputSheet = P001#P007#P034#P054
String [] arr  = roomProduct.split("#")
for(String a : arr) {
    ArrayList <String> list = new ArrayList<String>()
    list.addAll(a)

    log.info list
    log.info responseMap.keySet()

    if(responseMap.keySet().contains(list)) {
        log.info "Room Product present in the node"
    }
}

Any help would be appreciated.

cfrick
  • 35,203
  • 6
  • 56
  • 68
avidCoder
  • 440
  • 2
  • 10
  • 28

2 Answers2

2

You can use the containsAll method of Set, which takes a collection:

if(responseMap.keySet().containsAll(list)) {

Not sure your code compiles, but it could at least be simplified:

String hotelCFromInputSheet = 'P001#P007#P034#P054'
ArrayList <String> list  = Arrays.asList(roomProduct.split("#"))
boolean containsAll = responseMap.keySet().containsAll(list)
ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

In this line you check if keySet contains whole list:

if (responseMap.keySet().contains(list)) {
    log.info "Room Product present in the node"
}

I think that your intention was to check if it contains the String that has been added in loop that is currently being processed:

if (responseMap.keySet().contains(a)) {
        log.info "Room Product present in the node"
}

Also, in this line: list.addAll(a) you are really adding one String so it can be replaced with list.add(a) to make your code a bit clearer.

Edit: If you want to print values present in the ArrayList of Strings associated with the specified key, you might want to try using loop like this:

if (responseMap.keySet().contains(a)) {
    List<String> strings = responseMap.get(a);
    for (String s : strings) {
        System.out.println(s + ", ");
    }
} 
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
  • After this I want to print the values() of the keys which are present inside the inputJSON node. That means I want to print the values() for [P001] [P007] [P034] [P054]. – avidCoder Jan 02 '18 at 07:22
  • @Ashuans I edited my answer, you might want to have a look at it to check if it is what you were asking for. – Przemysław Moskal Jan 02 '18 at 08:58