我有一个方法从作为员工信息的对象集合中提取值:
public class Employee
{
public String AREA;
public String EMPLOYEE_ID;
public String EMPLOYEE_NAME;
}
Run Code Online (Sandbox Code Playgroud)
我想获得我所做的所有不同区域我认为更容易,只需检查ArrayList是否包含值,如果不是添加它,则需要187ms才能完成,:
long startTime = System.currentTimeMillis();
ArrayList<String> distinct_areas = new ArrayList<String>();
for (int i = 0; i < this.employeeTress.length; i++)
{
if (!distinct_areas.contains(this.employeeTress[i].AREA))
distinct_areas.add(this.employeeTress[i].AREA);
}
String[] unique = new String[distinct_areas.size()];
distinct_areas.toArray(unique);
long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) + "ms");
Run Code Online (Sandbox Code Playgroud)
然后我想以不同的方式做它,看它是否变得更快,排序数组然后只检查最后一项如果它不同然后添加它,它更快一点,它需要121ms才能完成:
startTime = System.currentTimeMillis();
String[] vs = new String[this.employeeTress.length];
for (int i = 0; i < this.employeeTress.length; i++)
{
vs[i] = this.employeeTress[i].AREA;
}
Arrays.sort(vs);
ArrayList<String> vsunique = new ArrayList<String>();
vsunique.add(vs[0]);
for (int i = 0; i < vs.length; i++)
{
if (!vsunique.get(vsunique.size()-1).equals(vs[i]))
{
vsunique.add(vs[i]);
}
}
String[] uni = new String[vsunique.size()];
vsunique.toArray(uni);
endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) + "ms");
Run Code Online (Sandbox Code Playgroud)
我是Java新手我想知道更好的方法.*注意,这段代码应该可以在android姜饼API LVL 10中使用.
Eri*_*low 10
如果要获取或计算员工列表中的不同区域,可以使用一组字符串.我正在更改变量名称以匹配Java标准.你可以事后得到计数.理想情况下,这些都是懒惰的方法.
public Set<String> areas(final List<Employee> employees) {
Set<String> areas = new HashSet<>();
for(final Employee employee: employees) {
areas.add(employee.getArea());
}
return areas;
}
Run Code Online (Sandbox Code Playgroud)
public Set<String> areas(final List<Employee> employees) {
return Sets.newHashSet(
Lists.transform(employees, new Function<Employee, String>() {
public String apply(Employee e) {
return e.getArea();
}
}));
}
Run Code Online (Sandbox Code Playgroud)
public Set<String> areas(final List<Employee> employees) {
return new HashSet<String>(employees.map(e => e.getArea()));
}
Run Code Online (Sandbox Code Playgroud)