Reputation:
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;
}
int count = getIndex(current.getValue(),list);
Collections.sort(list.subList(0, count),Comparator.<Pair<Integer,Integer>>comparingInt(Pair::getValue));
Stream API came into my mind. But after performing operations it doesn't manipulate the underlined collection.
Upvotes: 0
Views: 78
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