JAVA - 从String数组列表中删除元素

时间:2016-03-10 13:59:40

标签: java arrays arraylist

我有一个包含以下数据的数组列表;

[pagoda, hour, hour experience, pagoda, car, eatables, eatables water, walk, small, small garden, little, little hot, jungle, jungle beach, restaurant, ocean, local, room, morning, guy, pagoda small, small garden, hour experience, peaceful environment, view]

我想检查arraylist中的元素是否包含另一个元素的值,如果是,则删除长度较短的元素。

例如: - 查看上面的arraylist中的小时和小时经验。我需要删除小时元素的方法,并且只保留小时体验元素。

这就是我写的。但它并没有那么好用。

public void removeDuplicateKeywords(ArrayList<String> list){
        System.out.println(list);

        for(int i=0; i<list.size(); i++){
            String keyword = list.get(i);
            for(int j=i+1; j<list.size(); j++){
                if(keyword.equals(list.get(j))){
                    list.remove(j);
                }
                if(list.get(j).trim().contains(keyword.trim()) && list.get(j).length() > keyword.length()){

                    list.remove(i);
                }

            }

        }
        System.out.println(list);
    }

这将打印

[pagoda, hour, hour experience, pagoda, car, eatables, eatables water, walk, small, small garden, little, little hot, jungle, jungle beach, restaurant, ocean, local, room, morning, guy, pagoda small, small garden, hour experience, peaceful environment, view]

[hour, hour experience, car, eatables water, walk, little, little hot, jungle beach, restaurant, ocean, local, room, morning, guy, pagoda small, small garden, peaceful environment, view]

请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:2)

这是使用Java 8实现此目的的一种方法。

此解决方案区分大小写 - 如果需要,将其改进为不区分大小写应该是微不足道的。

// test list
List<String> duplicates = new ArrayList<>(
    Arrays.asList(
        new String[]{
            "pagoda", "hour", "hour experience", "pagoda", "car", "eatables", 
            "eatables water", "walk", "small", "small garden", "little", 
            "little hot", "jungle", "jungle beach", "restaurant", "ocean", 
            "local", "room", "morning", "guy", "pagoda small", "small garden", 
            "hour experience", "peaceful environment", "view"
        }
    )
);
// manipulating to Set with collections stream API
Set<String> noDuplicates = duplicates
    .stream()
    .filter(
        (s) -> duplicates.stream()
        // negative filter from original list
        .noneMatch(
            // condition: longer string that starts with current string
            (ss) -> ss.length() > s.length() && ss.startsWith(s)
        )
    )
    .collect(Collectors.toSet());

System.out.println(noDuplicates);

<强>输出

[hour experience, restaurant, guy, local, room, jungle beach, morning, little hot, 
pagoda small, peaceful environment, view, ocean, car, eatables water, 
small garden, walk]