Sandy
Sandy

Reputation: 323

How to get subset of values for a particular key in HashMap<String, Object> initialMap = new HashMap<String, Object>()

I am having a

HashMap<String, Object> initialMap = new HashMap<String, Object>();

in which I have set of string values for a key this way,

error=[e1, e2, e3, e4, e5, e6],[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24],[e25, e26, e27, e28, e29, e30], status=[s1, s2, s3, s4, s5, s6],[s7, s8 s9, s10, s11, s12],[s13, s14 ,s15, s16, s17, s18],[s19, s20, s21, s22, s23, s24],[s25, s26, s27, s28, s29, s30], data=[[d1, d2, d3, d4, d5, d6],[d7, d8, d9, d10, d11, d12],[d13, d14 ,d15, d16, d17, d18],[d19, d20, d21, d22, d23, d24],[d25, d26, d27, d28, d29, d30]], warning=[w1, w2, w3, w4, w5, w6],[w7, w8, w9, w10, w11, w12],[w13, w14 ,w15, w16, w17, w18],[w19, w20, w21, w22, w23, w24],[w25, w26, w27, w28, w29, w30]}

so, here for a key called error,

we have these 5 set of string values below.

[e1, e2, e3, e4, e5, e6],[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24],[e25, e26, e27, e28, e29, e30].

I do not need all these 5 set values for a key but i need to get using start and end limit i.e subset of values for each key.

Say if my startLimit=2 and endLimit=4 then i should get only 2,3,4 set of values for key error,

[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24]

like wise need to repeat for all other 3 keys also.

I tried this way but it is always giving me all the values of a particular key.

Is there any way to get subset of values for a particular key in hashmap?

Here is the code i tried,

public class MapTest {
        HashMap<String, Object> finalMap = new HashMap<String, Object>();
        int startLimit = 2;
        int endLimit = 4;

        public static void main(String[] args) {
            MapTest mm = new MapTest();
            mm.getData();
        }
        public void getData()
        {
            HashMap<String, Object> initialMap = new HashMap<String, Object>();
            initialMap.put("status","[s1, s2, s3, s4, s5, s6],[s7, s8 s9, s10, s11, s12],[s13, s14 ,s15, s16, s17, s18],[s19, s20, s21, s22, s23, s24],[s25, s26, s27, s28, s29, s30]");
            initialMap.put("data","[[d1, d2, d3, d4, d5, d6],[d7, d8, d9, d10, d11, d12],[d13, d14 ,d15, d16, d17, d18],[d19, d20, d21, d22, d23, d24],[d25, d26, d27, d28, d29, d30]]");
            initialMap.put("warning","[w1, w2, w3, w4, w5, w6],[w7, w8, w9, w10, w11, w12],[w13, w14 ,w15, w16, w17, w18],[w19, w20, w21, w22, w23, w24],[w25, w26, w27, w28, w29, w30]");
            initialMap.put("error","[e1, e2, e3, e4, e5, e6],[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24],[e25, e26, e27, e28, e29, e30]");

            Set<Entry<String, Object>> entries = initialMap .entrySet();
            for (Iterator<Entry<String, Object>> i = entries.iterator(); i.hasNext(); ) {
                Entry e = (Entry) i.next();
                if(e.getKey().equals("error"))
                {   
                    Object errValue = initialMap.get(e.getKey());
                    //System.out.println("errValue" + errValue);
                    finalMap.put(e.getKey().toString(), errValue);
                }
                if(e.getKey().equals("data"))
                {   
                    Object errValue = initialMap.get(e.getKey());
                    //System.out.println("errValue" + errValue);
                    finalMap.put(e.getKey().toString(), errValue);
                }
                else if(e.getKey().equals("warning"))
                {   
                    Object errValue = initialMap.get(e.getKey());
                    //System.out.println("errValue" + errValue);
                    finalMap.put(e.getKey().toString(), errValue);
                }
                if(e.getKey().equals("status"))
                {   
                    Object errValue = initialMap.get(e.getKey());
                    //System.out.println("errValue" + errValue);
                    finalMap.put(e.getKey().toString(), errValue);
                }
            }
            if(startLimit == 2 && endLimit == 4)
                System.out.println("final map after limiting the data " + finalMap);
        } 
    }

I am getting all the 5 pairs of values for a key this way from the above program,

final map after limiting the data

{error=[e1, e2, e3, e4, e5, e6],[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24],[e25, e26, e27, e28, e29, e30], status=[s1, s2, s3, s4, s5, s6],[s7, s8 s9, s10, s11, s12],[s13, s14 ,s15, s16, s17, s18],[s19, s20, s21, s22, s23, s24],[s25, s26, s27, s28, s29, s30], data=[[d1, d2, d3, d4, d5, d6],[d7, d8, d9, d10, d11, d12],[d13, d14 ,d15, d16, d17, d18],[d19, d20, d21, d22, d23, d24],[d25, d26, d27, d28, d29, d30]], warning=[w1, w2, w3, w4, w5, w6],[w7, w8, w9, w10, w11, w12],[w13, w14 ,w15, w16, w17, w18],[w19, w20, w21, w22, w23, w24],[w25, w26, w27, w28, w29, w30]}

BUt i need to get this way as my limit is 2 to 4 pairs,

final map after limiting the data {error=[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24], status=[s7, s8 s9, s10, s11, s12],[s13, s14 ,s15, s16, s17, s18],[s19, s20, s21, s22, s23, s24], data=[[d7, d8, d9, d10, d11, d12],[d13, d14 ,d15, d16, d17, d18],[d19, d20, d21, d22, d23, d24]], warning=[w7, w8, w9, w10, w11, w12],[w13, w14 ,w15, w16, w17, w18],[w19, w20, w21, w22, w23, w24]}

Can anyone help me in this issue?

Thanks

Upvotes: 1

Views: 1353

Answers (2)

Thomas Naskali
Thomas Naskali

Reputation: 581

note: I assumed the value associated to the "data" key had the same structure as the other values (no additional surrounding brackets), if it's not the case then the algorithm becomes a little more complicated.

I used guava and commons-lang3 on top of a JDK 6.

HashMap<String, Object> finalMap = Maps.newHashMap(Maps.transformValues(initialMap, new Function<Object, Object>() {
    public Object apply(Object input) {
        String inputAsString = (String) input;
        String trimmedInput = inputAsString.replaceAll("^\\[+", "").replaceAll("\\]+$", "");
        int removedBraces = (inputAsString.length() - trimmedInput.length()) / 2;
        List<String> splitInput = Lists.newArrayList(Splitter.on("],[").split(trimmedInput));
        List<String> subList = splitInput.subList(startLimit - 1, endLimit);
        return StringUtils.repeat('[', removedBraces) + Joiner.on("],[").join(subList)
        + StringUtils.repeat(']', removedBraces);
    }
}));

In short, this code creates a new map where every value in the new map is built by transforming the initial value using the following algorithm :

  1. take out the leading '[' and the trailing ']'
  2. split it by the "],[" string
  3. take a sublist of the resulting list (from startLimit - 1 to endLimit)
  4. join the list back together to a String using "],[", adding the initial leading '[' and trailing ']' back

Upvotes: 0

Marco Stramezzi
Marco Stramezzi

Reputation: 2281

I see 2 big problems in your code:

  1. startLimit and endLimit are not used to filter data extracted from initialMap but they are just tested on thei value; your code simply copy key/value from initialMap to finalMap and then print finalMap if the two limits are set to 2 and 4 (they are simply flag to decide whether to print or not
  2. each key in initialMap is associated with a String (not an Object or a List) so the only way I see to separate "square bracket objects" is playing with commas..but I am not sure if this is the goal of your code

I suggest you to change the map values to List<String> and rethink the logic of getData.

public static void main(String[] args) {
    int startLimit = 2;
    int endLimit = 4;

    HashMap<String, List<String>> finalMap = new HashMap<>();
    HashMap<String, List<String>> initialMap = new HashMap<>();

    List<String> sList = Arrays.asList("[s1, s2, s3, s4, s5, s6]", "[s7, s8, s9, s10, s11, s12]", "[s13, s14 ,s15, s16, s17, s18]", "[s19, s20, s21, s22, s23, s24]", "[s25, s26, s27, s28, s29, s30]");
    List<String> dList = Arrays.asList("[d1, d2, d3, d4, d5, d6]", "[d7, d8, d9, d10, d11, d12]", "[d13, d14 ,d15, d16, d17, d18]", "[d19, d20, d21, d22, d23, d24]", "[d25, d26, d27, d28, d29, d30]");
    List<String> wList = Arrays.asList("[w1, w2, w3, w4, w5, w6]", "[w7, w8, w9, w10, w11, w12]", "[w13, w14 ,w15, w16, w17, w18]", "[w19, w20, w21, w22, w23, w24]", "[w25, w26, w27, w28, w29, w30]");
    List<String> eList = Arrays.asList("[e1, e2, e3, e4, e5, e6]", "[e7, e8, e9, e10, e11, e12]", "[e13, e14 ,e15, e16, e17, e18]", "[e19, e20, e21, e22, e23, e24]", "[e25, e26, e27, e28, e29, e30]");

    initialMap.put("status", sList);
    initialMap.put("data", dList);
    initialMap.put("warning", wList);
    initialMap.put("error", eList);

    Iterator<Entry<String, List<String>>> i = initialMap.entrySet().iterator();
    Entry<String, List<String>> e = null;
    List<String> eValue = null;
    while (i.hasNext()) {
        e = i.next();
        eValue = e.getValue();
        finalMap.put(e.getKey(), eValue.subList(startLimit, endLimit));
    }
    System.out.println("final map after limiting the data " + finalMap);
} 

EDIT: if map values cannot be List<String> you can do as follows

public static void main(String[] args) {
    int startLimit = 2;
    int endLimit = 4;
    String objectSeparator = "],";

    HashMap<String, String> finalMap = new HashMap<>();
    HashMap<String, String> initialMap = new HashMap<>();

    String sList = "[s1, s2, s3, s4, s5, s6],[s7, s8 s9, s10, s11, s12],[s13, s14 ,s15, s16, s17, s18],[s19, s20, s21, s22, s23, s24],[s25, s26, s27, s28, s29, s30]";
    String dList = "[[d1, d2, d3, d4, d5, d6],[d7, d8, d9, d10, d11, d12],[d13, d14 ,d15, d16, d17, d18],[d19, d20, d21, d22, d23, d24],[d25, d26, d27, d28, d29, d30]]";
    String wList = "[w1, w2, w3, w4, w5, w6],[w7, w8, w9, w10, w11, w12],[w13, w14 ,w15, w16, w17, w18],[w19, w20, w21, w22, w23, w24],[w25, w26, w27, w28, w29, w30]";
    String eList = "[e1, e2, e3, e4, e5, e6],[e7, e8, e9, e10, e11, e12],[e13, e14 ,e15, e16, e17, e18],[e19, e20, e21, e22, e23, e24],[e25, e26, e27, e28, e29, e30]";

    initialMap.put("status", sList);
    initialMap.put("data", dList);
    initialMap.put("warning", wList);
    initialMap.put("error", eList);

    Iterator<Entry<String, String>> it = initialMap.entrySet().iterator();
    Entry<String, String> e = null;
    String eValue = null;
    String[] splitted = null;
    while (it.hasNext()) {
        e = it.next();
        eValue = e.getValue();

        // Split each "square bracket object" in a separate string 
        splitted = eValue.split(objectSeparator);

        // Create a new string containing only objects with index between limits
        String limited = "";
        for(int idx = startLimit-1; idx <= endLimit-1; idx++)
            limited += (splitted[idx] + objectSeparator);

        // Remove trailing comma added inside for loop
        limited = limited.substring(0, limited.lastIndexOf(","));

        finalMap.put(e.getKey(), limited);
    }
    System.out.println("final map after limiting the data " + finalMap);
} 

Upvotes: 1

Related Questions