[FIXED] Effective way. of comparing list elements in Java

Issue

Is there any **effective way **of comparing elements in Java and print out the position of the element which occurs once.
For example: if I have a list: ["Hi", "Hi", "No"], I want to print out 2 because "No" is in position 2. I have solved this using the following algorithm and it works, BUT the problem is that if I have a large list it takes too much time to compare the entire list to print out the first position of the unique word.

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

for (int i = 0; i < strings.size(); i++) {
    int oc = Collections.frequency(strings, strings.get(i));
    if (oc == 1)
        System.out.print(i);
        break;
}

Solution

I can think of counting each element’s occurrence no and filter out the first element though not sure how large your list is.

Using Stream:

List<String> list = Arrays.asList("Hi", "Hi", "No");
//iterating thorugh the list and storing each element and their no of occurance in Map
Map<String, Long> counts = list.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
String value = counts.entrySet().stream()
                    .filter(e -> e.getValue() == 1) //filtering out all the elements which have more than 1 occurance
                    .map(Map.Entry::getKey) // creating a stream of element from map as all of these have only single occurance
                    .findFirst() //finding the first element from the element stream
                    .get();
System.out.println(list.indexOf(value));

EDIT:
A simplified version can be

Map<String, Long> counts2 = new LinkedHashMap<String, Long>();
for(String val : list){
    long count = counts2.getOrDefault(val, 0L);
    counts2.put(val, ++count);
}
for(String key: counts2.keySet()){
    if(counts2.get(key)==1){
        System.out.println(list.indexOf(key));
        break;
    }
}

The basic idea is to count each element’s occurrence and store them in a Map.Once you have count of all elements occurrences. then you can simply check for the first element which one has 1 as count.

Answered By – Sayan Bhattacharya

Answer Checked By – Mary Flores (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published