user8838577
user8838577

Reputation:

Create a sub-list according to criteria and Perform operations

I have sorted List<Pair<Integer, Integer>> and I want to create a subList for all the Pairs which having a key less than one arbitrary value k.

I want to create a subList that follows above condition and sort it.

I did something like this -

//to get the max index of the List
public static int getIndex(List<Pair<Integer,Integer>> list,int key)
{
   int count=0;
   for(Pair<Integer,Integer> p: list)
   {
       if(p.getKey()>key)
         break;                 
    count++;
     }
   return count;
} 

Now, Sorting subList as per this criteria

 int count = getIndex(current.getValue(),list);
 Collections.sort(list.subList(0, count),Comparator.<Pair<Integer,Integer>>comparingInt(Pair::getValue));

Is there any elegent way to do achieve this ? I mean java 8 way.

Stream API came into my mind. But after performing operations it doesn't manipulate the underlined collection.

Upvotes: 0

Views: 78

Answers (1)

WJS
WJS

Reputation: 40062

Something like the following.

  List<Pair<Integer,Integer>> subList = 
                 list.stream()
                     .filter(p->p.getKey() <  key)
                     .collect(Collectors.toList());

This works regardless of the ordering of the pairs in the list. It constructs the new list as each pair passes thru the filter.

Upvotes: 2

Related Questions