根据条件创建子列表并执行操作

时间:2019-08-28 13:17:17

标签: java

我已经对List<Pair<Integer, Integer>>进行了排序,并且希望为所有对的键小于一个任意值k的对创建一个子列表。

  

我想创建一个符合上述条件的子列表并对其进行排序。

我做了这样的事情-

//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));

是否有任何其他方法可以做到这一点?我的意思是Java 8方式。

Stream API浮现在我的脑海。但是执行操作后,它不会处理带下划线的集合。

1 个答案:

答案 0 :(得分:1)

类似以下内容。

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

无论列表中对的顺序如何,此方法均有效。当每个pair通过过滤器时,它都会构造新列表。

相关问题