如何将对象转换为带键的列表



我有一个如下格式的列表

[{name=test1, id=something, row=1},
{name=test3, id=something, row=3},
{name=test2, id=something, row=2},
{name=test4, id=something, row=4}]

我怎么能找到值根据它的键,例如,我需要名字从第3行…以及如何根据row

进行排序

由于您的示例不是有效的json,我认为这应该只是表示对象的结构。因此,对于一个带有这个类的对象的列表

public class NamedRow {
private String name;
private String id;
private int row;
public int getRow() {
return row;
}
// Other getters + setters
}

你可以用java流来解决这个问题:

  • 假设行值唯一:
// return null if not found
public static NamedRow findSingle(List<NamedRow> list, int row){
return list.stream()
.filter(namedRow -> namedRow.getRow() == row)
.findAny()
.orElse(null);
}
  • 假设row的值为而不是唯一:
// returns empty list if no entry matches
public static List<NamedRow> findMultiple(List<NamedRow> list, int row){
return list.stream()
.filter(namedRow -> namedRow.getRow() == row)
.collect(Collectors.toList());
}

最新更新