简体   繁体   English

获取数组中字符串的索引,并在其他数组中删除这些索引处的字符串

[英]get index of string in Array and delete in an other Array the strings at these indexes

I have two arrays : 我有两个数组:

String[] dishes = {"Dish1", "Dish2", "Dish3", "Dish4", "Dish5", "Dish6"};
String[] dishCategory = {"daily Dish", "daily Dish", "daily Dish", "side Dish", "side Dish", "Dish special"};

As result I want two Arrays: one with the daily dishes and the dish special in it, and the other one only with the side dishes. 结果,我需要两个数组:一个包含日常菜肴和其中的特殊菜肴,另一个则仅包含配菜。

That's why I tried to get the "side Dish" index of the dishCategory to delete these Strings of my dishes Array. 这就是为什么我尝试获取dishCategory的“ side Dish”索引来删除我的菜式Array的这些字符串的原因。 But I even couldn't work out a function to get all the "side dish" indexes. 但是我什至无法计算出所有“配菜”索引的函数。

Does anyone know a good solution? 有谁知道一个好的解决方案?

The easiest way to do this to create 2 new arrays. 创建2个新阵列的最简单方法。

List<String> dailyAndSpecialList = new ArrayList<>();
List<String> sideList = new ArrayList<>();
for (int i = 0; i < dishCategory.length; i++) {
  if (dishCategory[i].equals("side Dish")) {
    sideList.add(dishes[i]);
  } else {
    dailyAndSpecialList.add(dishes[i]);
  }
}
String[] sideArray = sideList.toArray(new String[sideList.size()]);
String[] dailyAndSpecialArray = dailyAndSpecialList.toArray(new String[dailyAndSpecialList.size()]);

You could iterate through the dishCategory array and compare the element of array with your "side dish" and store the matching index in other Arraylist and later on using these index , you can remove or do whatever you want to do. 您可以遍历dishCategory数组,并将array的元素与您的“配菜”进行比较,并将匹配的索引存储在其他Arraylist中,以后再使用这些索引,您可以删除或做任何您想做的事情。

sample code :- 示例代码:-

ArrayList<Integer> sideDishIdx = new ArrayList<>();
        int i=0;
        for(String s : dishCategory){
            if(s.equalsIgnoreCase("side Dish"))
                sideDishIdx.add(i);
            i++;

        }
        for(Integer idx : sideDishIdx){
            System.out.println("idx "+idx);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM