1

I would like filter ArrayList by spotting the similar items positions in ArrayList so I can get the index position of duplicate items.

With a list like:

List = ['A', 'B', 'A', 'C', 'E', 'A']

I want it to give me:

index [0, 2, 5] // A
index [1] // B
index [3] // C
index [4] // E
4
  • 4
    What you have tried so far?? Commented Dec 12, 2016 at 6:17
  • I tried to check and find duplicated items and put it in different array then remove the duplication and search again using these values one by one. if value 1 (from the duplicates Array) matches the value of current index //do something here but sadly it didn't work if statement here runs only once Commented Dec 12, 2016 at 6:25
  • Share your code.. Commented Dec 12, 2016 at 6:26
  • Read guidelines for posting homework questions here: meta.stackoverflow.com/questions/334822/… Commented Dec 12, 2016 at 7:23

3 Answers 3

4
Map<Character, List<Integer>> indexes = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
    indexes.computeIfAbsent(list.get(i), c -> new ArrayList<>()).add(i);
}
System.out.println(indexes);
// {A=[0, 2, 5], B=[1], C=[3], E=[4]}
Sign up to request clarification or add additional context in comments.

Comments

1
char[] list = {'A', 'B', 'A', 'C', 'E', 'A'};
    Map<Character, List<Integer>> indexes = new HashMap<>();
    for (int i = 0; i < list.length; i++) {
         if(indexes.get(list[i]) != null)
         { 
             List<Integer> indexList=indexes.get(list[i]);
             indexList.add(i);
             indexes.put(list[i],indexList);
         }
         else
         {
            List<Integer> indexList =  new ArrayList<>();
            indexList.add(i);
             indexes.put(list[i],indexList);
        }
    }
    System.out.println(indexes);
    // {E=[4], A=[0, 2, 5], B=[1], C=[3]}

1 Comment

So much redundant code. All you need inside the loop is: List<Integer> indexList = indexes.get(list[i]); if (indexList == null) indexes.put(list[i], indexList = new ArrayList<>()); indexList.add(i);
1

Java 8+

We can use Streams with Collectors.groupingBy to obtain all the indexes of a particular element in a List.

import java.util.stream.Collectors;
import java.util.stream.IntStream;
//...
final Map<Character, List<Integer>> indexMap = IntStream.range(0, list.size()).boxed()
        .collect(Collectors.groupingBy(list::get));
//{A=[0, 2, 5], B=[1], C=[3], E=[4]}
//Map of item value to List of indexes at which it occurs in the original List

Demo

Comments

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.