[英]Sorting an array of sentence according to the original sentence array
我有一个SENTENCE1数组,其中包含一些句子:
String[] SENTENCE1 = new String[]{
"This book is nice",
"I like it",
"I read them alot",
"My favourite book",
"I put it in a shelf"};
接下来,我还有一个句子数组,该句子是从SENTENCE1数组(称为SENTENCE2)中随机获得的:
String[] SENTENCE2 = new String[]{
"I put it in a shelf" ,
"I like it",
"My favourite book"};
如何根据SENTENCE1中的出现顺序对SENTENCE2数组进行排序,以便SENTENCE2中的输出为:
I like it
My favourite book
I put it in a shelf
无论如何,我试图做到这一点并遍历它们,但它显示了数组超出范围。
for (int g=0;g<SENTENCE2.length;g++){
for (int o=0;o<SENTENCE1.length;o++)
{
if (SENTENCE2[g].contains(SENTENCE1[o])){
System.out.println(SENTENCE2[g])
}
}
}
谢谢您的帮助。
您的代码是正确的,一件事是,如果要完成String的完全匹配,则不需要contains
。 使用equals
for(int i = 0; i < sent1.length; i++){
for(int j = 0; j < sent2.length; j++){
if(sent1[i].equals(sent2[j])){
System.out.println(sent2[j]);
}
}
}
始终在Java中使用骆驼大小写作为局部变量
尝试这个。
List<String> list = Arrays.asList(SENTENCE1);
String[] sorted = Stream.of(SENTENCE2)
.sorted(Comparator.comparing(s -> list.indexOf(s)))
.toArray(String[]::new);
System.out.println(Arrays.toString(sorted));
// -> [I like it, My favourite book, I put it in a shelf]
TreeMap<Integer, String> map = new TreeMap<>();
for (int i=0;i<SENTENCE2.length;i++) {
for (int j = 0; j < SENTENCE1.length; j++) {
if (SENTENCE2[i].equals(SENTENCE1[j])) {
map.put(j, SENTENCE2[i]);
}
}
}
map.values().toArray(SENTENCE2);
for(String value: SENTENCE2){
System.out.println(value);
}
在TreeMap
值将自动按键排序。
如果您愿意使用google guava这样的外部库。 可以像下面这样轻松完成:
public static void main(String[] args) {
String[] SENTENCE1 = new String[]{
"This book is nice",
"I like it",
"I read them alot",
"My favourite book",
"I put it in a shelf"};
String[] SENTENCE2 = new String[]{
"I put it in a shelf",
"I like it",
"My favourite book"};
Comparator<String> SENTENCE1_COMPARATOR = Ordering.explicit(Arrays.asList(SENTENCE1));
Arrays.sort(SENTENCE2, SENTENCE1_COMPARATOR);
System.out.println(Arrays.toString(SENTENCE2));
}
您可以这样:
@Test
public void test() {
String[] SENTENCE1 = new String[]{
"This book is nice",
"I like it",
"I read them alot",
"My favourite book",
"I put it in a shelf"};
String[] SENTENCE2 = new String[]{
"I put it in a shelf",
"I like it",
"My favourite book"};
System.out.println(SENTENCE1.length);
for(int i= 0 ;i<SENTENCE1.length;i++){
boolean flag = false;
for(int j = 0; j<SENTENCE2.length;j++){
if(SENTENCE2[j].equals(SENTENCE1[i])){
flag = true;
break;
}
}
if(!flag){
SENTENCE1[i]=null;
}
}
for(int k=0;k<SENTENCE1.length;k++){
if(SENTENCE1[k]!=null)
System.out.println(SENTENCE1[k]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.