1

At first Sorry if title doesn't really explain the problem as it should be.

I have 2 ArrayList in my android (java) code

as example lets say the first is made of strings and the second is made of integers.

ArrayLis<String> strings = new ArrayList<String>();
strings.add("s1");
strings.add("s2");
strings.add("s1");
strings.add("s3");
strings.add("s4");
strings.add("s1");
strings.add("s2");

ArrayList<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
ints.add(5);
ints.add(3);
ints.add(4);
ints.add(3);
ints.add(2);

Taking this example, lets say each value in array list strings correspond to a value of array ints but the int value might change

I want to remove the repetition in the string array, I used LinkedHashSet to do so:

LinkedHashSet<String>hashset = new LinkedHashSet<>(strings);
strings = new ArrayList<> hashset;

The issue now is i removed the duplicate string entries but i also removed the link between each string and its int value.

how can I get the new "ints" array using the minimal int value for the string for example for s1 that has 1, 5 and 3 as bound values get the 1 value as so:

strings = ["s1", "s2", "s3", "s4"];
ints = [1, 2, ,3, 4];

I thought of using maps. but is it the best way to do it? (map the string to the int and whenever a repetition occures check int if smaller and replace map value)

1 Answer 1

1

I'd iterate over the string list and convert it to a linked map for the string value to the minimal int. Once that's done, if you really want to, you could re-create the two lists:

Map<String, Integer> map = new LinkedHashMap<>();
for (int index = 0; index < strings.size(); ++i) {
    final int i = index;
    map.compute(
        strings.get(i), (k, v) -> v == null ? ints.get(i) : Math.min(v, ints.get(i)));
}

// If you want two lists again:
strings = new ArrayList<>(map.keySet());
ints = new ArrayList<>(map.values());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. but i faced some issue with it. i am using 1.7 java so lambdas cant be used. also i am targetting os 5 (API 21) and compute will require 24. But i followed the Main idea behind it (the MAP) and it worked with me. Thanks again. (PS: in your response the loop will never be used as it is used on a new map of size 0)
@EYakoumi yikes, thanks for noticing! It was supposed to loop until strings.size(), not map.size(). Edited and fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.