ralhanani
ralhanani

Reputation: 35

Comparator to get the maximum value in Linked List with exclude the first element of the Linked List from the comparison

I am trying to extract the maximum value from the LinkedList,but with one condition that I want the first element of the LinkedList being out of the comparison and without relying on the values stored inside the first element. Can I use the index of the LinkedList or whatever to exclude the first element through the comparison. This is what I have done but I do not know how implement this condition:

import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class HelloWorld{

    public static void main(String args[]) {
      // create a linked list

    LinkedList<HashMap<Integer, Integer>> PathList = new LinkedList<HashMap<Integer, Integer>>();
    Integer n = new Integer(0);
      // add elements to the linked list

    for(int i=1; i<4; i++){
        HashMap<Integer, Integer> PMap = new HashMap<Integer, Integer>();
        PMap.put(1,0);
        PMap.put(2,i);
        PMap.put(3,2*i);
        PathList.add(n,PMap);
        n++;        
                }

   Iterator x = PathList.listIterator(0);
   // print list with the iterator
   while (x.hasNext()) {
     HashMap<Integer, Integer> PMap = new HashMap<Integer, Integer>();
     PMap = (HashMap<Integer, Integer>)x.next();
   System.out.println(PMap.get(3));
   }
    Comparator<HashMap> cmp = new Comparator<HashMap>() {
        @Override
    public int compare(HashMap hm1, HashMap hm2) {

    return new Integer((Integer)hm1.get(3)).compareTo(new Integer((Integer)hm2.get(3)));
    } 
    };  
    System.out.println("Max value in this element " + Collections.max(PathList,cmp));

   }

}

Upvotes: 0

Views: 398

Answers (2)

Saj
Saj

Reputation: 18712

Aside from Collections.max, you can do the implementation your own like this-

public int getMaxValue(LinkedList<Integer> list){
    int max = Integer.MIN_VALUE;
    /* We used i = 1 below to exclude first element as your needs. 
       But to include all elements, use i = 0 */
    for(int i = 1; i < list.size(); i++){
        if(list.get(i) > max){
            max = list.get(i);
        }
    }
    return max;
}

Note that calling the above method with zero or one item in the list will return the Integer.MIN_VALUE which is -2147483648.

Upvotes: 0

user3707125
user3707125

Reputation: 3484

You can create a sublist from the original list (it is just a view, it doesn't copy all the elements).

So you can change:

System.out.println("Max value in this element " + Collections.max(PathList,cmp));

To:

LinkedList<HashMap<Integer, Integer>> pathListWithoutFirst = PathList.subList(1, PathList.size());
System.out.println("Max value in this element " + Collections.max(pathListWithoutFirst, cmp));

Upvotes: 2

Related Questions