好的,这是我的要求,我有下表:
ID-Category-No 22-Software-1 45-Software-2 78-Hardware-3 48-Software-4 11-Hardware-5 91-Service -6 95-Service -7 93-Software-8
I select all data with order by No, & put it into a String[], then put this String[] int a list
So I will have:
String[] s1={"22","Software","1"};
String[] s2={"45","Software","2"};
.....
List<String[]> myL=new ArrayList<String[]>();
myL.add(s1);
myL.add(s2);
....
现在,来自 myL
,我只想把所有有Category的String[]连续取出,如果category不连续,则去掉。
注意:我们必须取最先出现的类别&所有连续出现的同一类别。所以我们需要做一些事情,以便最终的 myL
将只包含这些 String[]
ID-Category-No 22-Software-1 45-Software-2 78-Hardware-3 91-Service -6 95-Service -7
最佳答案
如果你不想让任务复杂化,你真的应该创建一个类,比如 Job
, 来存储这些属性,而不是使用 String[]
.然后维护一个List<Job>
.
在Job
类,你应该实现 equals()
和 hashCode()
方法,比较基于 category
.因此,该类将如下所示:
class Job {
private int id;
private String category;
private int no;
public Job(int id, String category, int no) {
this.id = id;
this.category = category;
this.no = no;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Job)) return false;
return category.equals(((Job)obj).category);
}
@Override
public int hashCode() {
return category.hashCode();
}
@Override
public String toString() {
return "[" + id + ", " + category + ", " + no + "]\n";
}
}
现在,您可以拥有一个 List<Job>
:
Job s1= new Job(22,"Software",1);
Job s2= new Job(45,"Software",2);
Job s3= new Job(78, "Hardware", 3);
Job s4= new Job(48, "Software", 4);
Job s5= new Job(11, "Hardware", 5);
Job s6= new Job(91, "Service", 6);
Job s7 =new Job(95, "Service", 7);
Job s8 = new Job(93, "Software", 8);
List<Job> list=new ArrayList<Job>(Arrays.asList(s1, s2, s3, s4, s5, s6, s7, s8));
创建临时 ArrayList
,它将存储您的结果:
List<Job> contiguous = new ArrayList<Job>();
/* The boolean variable will be used to track whether the sequence till
now is contiguous or not */
/* Everytime we add a new unique job, a new contiguous sequence is started.
So, we will set this variable to `true` */
boolean isContiguousTillNow = false;
这是执行实际工作的循环:
for (Job job: list) {
if (contiguous.isEmpty()) {
/* First job added. Set 'isContiguousTillNow' to 'true' */
contiguous.add(job);
isContiguousTillNow = true;
} else if (isContiguousTillNow && contiguous.get(contiguous.size() - 1).equals(job)) {
/* The sequence has been contiguous till now, and the last job
added is equal to current job. Add the job. */
contiguous.add(job);
} else if (!contiguous.contains(job)) {
/* Sequence is either broken here, or was already broken */
/* But since the list doesn't already contains this job, add it,
and this starts a new contiguous sequence. So, set it to 'true' */
contiguous.add(job);
isContiguousTillNow = true;
} else {
/* ContigousSequence stops here. So, set it to 'false' */
isContiguousTillNow = false;
}
}
然后是你的 contiguous
列表将包含所需的结果。
关于java - 如何检查字符串数组的连续性&如果不连续,则将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064253/