简体   繁体   中英

How to dynamically change a list value to another list in Java or Groovy

For Example, I have a list like below,

list1 = ["a","b","c"] now i want to add value to the list[1] index and that index will be another list like,

list2 = ["w","x","y"]

The output will be ["a",["b","w","x","y"],"c"] I don't want to replace 1 index

Is it possible?

It's possible, but not very type safe (= don't do it ). You could use a List and then add your values, which could be any type of Object (Integer String... or another List). When retrieving the Objects you would need to check what type they are with instanceof and then cast them.

In java it is not possible taking type of list1 as String .
Type of list1 seems String and you are adding another list into list1 which is not correct.

But it is possible taking type list1 as Object

List<Object> list1=new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");

List<Object> innerlist=new ArrayList<>();  //Inner List

list1.add(innerlist);

However it is not recommended way.

You can add value to a specific index as below

    List list = new ArrayList();
    List l1 = new ArrayList();
    l1.add("3");
    l1.add("4");
    list.add("1");
    list.add("5");
    list.add(1, l1);

Please make sure that index in the list size, otherwise will get the IndexOutOfBoundsException

Please try below logic

public List replaceIndex(List original, List replace, int index) {
    Object object = original.remove(index);
    replace.add(0, object);
    original.add(index, replace);
    return original;
}

Your base list contains two types: String and List<String>

You can create a list as your base list in java but is not a good idea because you are mixing types. That is a bad practice. You should avoid raw types .

You could use a helper method like :

private static List mergeIntoList(List source, List listToAdd, int index) {
    List innerList = new ArrayList(listToAdd);
    innerList.add(0, source.get(index));

    List mergedList = new ArrayList(source);
    mergedList.set(index, innerList);

    return mergedList;
}

Exemple:

 List source = Arrays.asList("a", "b", "c");
 List listToAdd = Arrays.asList("w", "x", "y");

 System.out.println(mergeIntoList(source, listToAdd, 1));

output: [a, [b, w, x, y], c]

But I repeat, you should avoid raw types, so this solution is not recommended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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