Java List insert element by index returned from binary search

Description

Java List insert element by index returned from binary search

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Main {
  public static void main(String args[]) {
    String langArray[] = { "CSS", "HTML", "Java", "Javascript", "SQL",
        "C++", "C" };

    // Convert to list
    List<String> list = new ArrayList<>(Arrays.asList(langArray));

    // Ensure list sorted
    Collections.sort(list);/*from   w  w w  . jav a  2  s  . com*/
    System.out.println(list);

    // Search for element in list
    int index = Collections.binarySearch(list, "CSS");
    System.out.println("Found CSS @ " + index);

    // Search for element not in list
    
    String newValue = "demo2s.com";
    index = Collections.binarySearch(list, newValue);
    System.out.println(newValue + " @ " + index);

    // Insert
    int newIndex = -index - 1;
    list.add(newIndex, newValue);
    System.out.println(list);
  }
}



PreviousNext

Related