Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

java - How to remove sequence of two elements from array or list?

How to remove two successive elements from array or list?

I've got an array:

new String[]{"FIRST", "SECOND", "SECOND", "THIRD", "FOURTH", "FIRST", "FOURTH"});

I should remove two successive elements from this array.

Elements to remove: "FIRST", "SECOND"

after removing elements new array or list should look like:

new String[]{"SECOND", "THIRD", "FOURTH", "FIRST", "FOURTH"});

now I've got: "SECOND", "FIRST"

result: new String[]{"FOURTH", "FIRST", "FOURTH"})

This is my code:

String[] s1 = new String[arr.length];

String n = "FIRST";
String s = "SECOND";
String w = "THIRD";
String e = "FOURTH";


//I found two successive elements, and element next to them 
//My question is, how can I remove these element from list, 
//or copy array without these elements to a new array?

for (int i = 0; i < arr.length; i++) {
    if (arr[i].equals(n) && arr[i + 1].equals(s)) {
        System.out.println(arr[i + 2]);
    }
}

How to remove two successive elements from array or list?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
public static void main(String[] args) {
    String[] arr = new String[]{"FIRST", "SECOND",
            "SECOND", "THIRD", "FOURTH", "FIRST", "FOURTH"};
    String[] toRemove = new String[]{"FIRST", "SECOND"};
    arr = removeSuccessive(arr, toRemove);
    System.out.println(Arrays.toString(arr));
}

private static String[] removeSuccessive(String[] arr, String[] toRemove) {
    ArrayList<String> res = new ArrayList<>();
    for (int i = 0; i < arr.length; i++) {
        if (!arr[i].equals(toRemove[0]))
            res.add(arr[i]);
        else if (i + 1 < arr.length && !arr[i + 1].equals(toRemove[1]))
            res.add(arr[i]);
        else
            i++;
    }
    return res.toArray(new String[res.size()]);
}

You can check and run this code here: https://ideone.com/v6nPRf


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...