Itemgetter(i)for java

时间:2017-05-16 19:16:54

标签: java list

我最近学会了使用ìtemgetter(i)来获取python中多个列表中的第i个元素。例如:

j_column=list(map(itemgetter(j), board[i+1:]))

board[i+1]部分返回了一个列表列表,每个列表代表第i行下面的水平行,板子的子部分,上面的代码返回该子部分的第j列。

现在我正在做类似的事情,我必须在一个列表中获取n个列表的第i个元素。我不知道但我必须用Java做这件事。我现在正在寻找相当于itemgetter(i)函数但在Java中

更多信息:

假设我有一个列表列表,例如:my_list将输出[[1,4,5,6,7],[3,0,0,9,8,4],[1,4,5]],我正在寻找的函数被称为someFunction,我想要每个子列表中的第3个数字,意思是每个子列表中索引2处的每个元素,这就是我正在寻找的:

 somefunction(2, my_list); //this would output [5,0,5]

2 个答案:

答案 0 :(得分:1)

正如您在评论中指定的那样,

  • 有一个List<List<Something>>
  • 想要从每个列表中检索i个元素,将其添加到新的List<Something>并返回该列表。

此代码应该足够了:

/**
 * Method is parameterized in the list-type, thus achieving maximal type checking. If the
 * inner lists are of different types, the inner lists must be of type List<Object>,
 * other types will not work. Type-checking is out of the window at that point.
 *
 * @param lists the list of lists, non-null and not containing null's.
 * @param i     the index to pick in each list, must be >= 0.
 * @param <T>   generic parameter of inner lists, see above.
 * @return      a List<T>, containing the picked elements.
 */
public static <T> List<T> getIthOfEach(List<List<T>> lists, int i) {
    List<T> result = new ArrayList<T>();

    for(List<T> list : lists) {
        try {
            result.add(list.get(i)); // get ith element, add it to the result-list
        // if some list does not have an ith element, an IndexOutOfBoundException is 
        // thrown. Catch it and continue.
        } catch (IndexOutOfBoundsException e) { } 
    }
    return (result);
}

您可以这样调用此方法:

List<Integer> everyFifthInteger = getIthOfEach(listOfListsOfIntegers, 5);
List<Object>  everyFifthThing   = getIthOfEach(listOfListsOfthings, 5);

答案 1 :(得分:1)

我在Java中使用高阶函数的经验非常有限(坦率地说,从Python过渡有点痛苦)但这在Python中模仿itemgetter,尽管它只接受单个参数而{{1在Python中使用变量数量的参数,但如果你真的想要它,你可以自己实现这个功能(虽然,我不确定应该返回什么样的容器类型,Python使用元组,我不知道什么是好的替代将在Java):

itemgetter

输出:

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.function.Function;

class Main {
  public static <T> List<T> asList(T ... items) {
    List<T> list = new ArrayList<T>();
    for (T item : items) {
        list.add(item);
    }
    return list;
  }
  public static <T> Function<List<T>, T> itemgetter(int i){
    Function<List<T>, T> f = l -> l.get(i);
    return f;
  }

  public static void main(String[] args) {
    List<List<Integer>> myList = asList(
        asList(1,4,5,6,7),
        asList(3,0,0,9,8,4),
        asList(1,4,5)
      );
    List newList = myList.stream()
                          .map(itemgetter(2))
                          .collect(Collectors.toList());
    System.out.println(newList);

  }
}