我有一个包含以下元素的数组列表:
List<Record> list = new ArrayList<>();
list.add(new Record(3, "32"));
list.add(new Record(4, "42"));
list.add(new Record(1, "12"));
list.add(new Record(1, "11"));
list.add(new Record(2, "22"));
list.add(new Record(5, "52"));
list.add(new Record(5, "53"));
list.add(new Record(5, "51"));
Run Code Online (Sandbox Code Playgroud)
Record是一个简单的POJO,它有id和name
我想在列表中做那些.
创建一个像Map<Integer, List<Record>>这样的地图有一个密钥是id和更细的密钥添加为列表.我已经做了如下.
Map<Integer, List<Record>> map = list.stream()
.collect(Collectors.groupingBy(Record::getId, HashMap::new, Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)现在我想按名称和子列表对列表进行排序,以提供内部限制
map.forEach((k, v) -> v.stream().sorted(Comparator.comparing(Record::getName)));
map.forEach((k, v) -> map.put(k, v.subList(0, Math.min(**limit**, v.size()))));
Run Code Online (Sandbox Code Playgroud)我已经尝试过,看起来这不是一个好方法.有谁能建议更好的方法?
我有一个方法,用于ServiceLoader使用资源加载服务.
public List<String> getContextData(int Id)
{
List<String> list = new ArrayList<String>();
ServiceLoader<ContextPlugin> serviceLoader = ServiceLoader.load(ContextPlugin.class);
for (Iterator<ContextPlugin> iterator = serviceLoader.iterator(); iterator.hasNext();)
{
list .addAll(iterator.next().getContextData(Id));
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
我应该如何使用Junit对上述方法进行单元测试?
我有一个像这样的对象
public class Keyword
{
private int id;
private DateTime creationDate
private int subjectId
...
}
Run Code Online (Sandbox Code Playgroud)
所以现在我有像下面这样的数据列表
KeywordList = [{1,'2018-10-20',10},{1,'2018-10-21',10},{1,'2018-10-22',10},{1,'2018 -10-23' ,20},{1, '2018年10月24日',20} {1, '2018年10月25日',20},{1, '2018年10月26日',30}, {1, '2018年10月27日',30},{1, '2018年10月28日',40}]
我想限制主题ID的这个列表
例如:如果我提供限制为2,它应该只包括每个主题id的最新2条记录,通过creationDate排序并将结果也作为列表返回.
resultList = KeywordList = [{1,'2018-10-21',10},{1,'2018-10-22',10},{1,'2018-10-24',20},{1, '2018年10月25日',20},{1, '2018年10月26日',30},{1, '2018年10月27日',30},{1, '2018年10月28日', 40}]
我们如何在Java 8中实现这种功能我已经以这种方式实现了它.但我对这段代码的性能有所怀疑.
dataList.stream()
.collect(Collectors.groupingBy(Keyword::getSubjectId,
Collectors.collectingAndThen(Collectors.toList(),
myList-> myList.stream().sorted(Comparator.comparing(Keyword::getCreationDate).reversed()).limit(limit)
.collect(Collectors.toList()))))
.values().stream().flatMap(List::stream).collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud)