set first element of a List [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following List:
private String[] myArray = new String[]{"A","B","C"} ;
List myList = new ArrayList();
for (int i = 0; i < myArray.length; i++) {
myList.add(myArray[i]);
}
There is a method that returns an element of the myList
String returnValue=myMethod();
returnValue could be A or B or C
returnValue should be the first element of the List
myList.add(0, returnValue);
Issue is if returnValue="B" ,myList becomes {"B","B","C"}.
I could explicitly remove the returnValue and add it again to myList. But it seems rather redundant ,can anybody suggest a better design approach.
My Required Result would be {"B","A","C"}

As far as I understood, you want the returnValue to become the first element of the List, i.e. change the order.
This can be achieved by using:
Collections.swap(myList, 0, myList.indexOf(returnValue));
Since this does not use adding nor removing, it allows to simplify your entire code:
List<String> myList = Arrays.asList("A","B","C");
String returnValue=myMethod();
Collections.swap(myList, 0, myList.indexOf(returnValue));
Note that this changes the order of the remaining elements. If you want to retain the order of all elements but the one you move to the front of the list (like remove followed by add would do) you need to use rotate:
List<String> myList = Arrays.asList("A","B","C");
String returnValue=myMethod();
Collections.rotate(myList.subList(0, myList.indexOf(returnValue)+1), 1);
But using swap will be faster on large lists, so if you don’t need the remaining elements to retain the original order, using swap is recommended.

List.add(index, element) doesn't replace the first element in your List, it inserts and thereby it moves all the following elements. You would end up with 4 entries in your list:
{RETURNVALUE, "A","B","C"}
There's also a replacing variant: List.set(index, element). With that you would end uo with 3 entries in your list:
{RETURNVALUE,"B","C"}
If you want to keep your List all sorted, there's the simple utility method
Collections.sort(mylist);
that sorts your collection in respect of it's element's compareTo() method, which would be a simple String ordering in your case.
If your RETURNVALUE is B and you've inserted the element, you would end up with
{"A","B","B","C"}

If I good understand your problem, you should use set(int index, E element) method to replace given element in your list

Related

Convert List<List<String>> to String[][] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How might I convert List<List<String>> to String[][]?
I've played around with the solutions provided here but not having much luck.
Any help would be appreciated.
Explanation
You can not just apply outer.toArray(...) because that would give you an array of lists, List<String>[].
You have to first convert all the inner lists before you can collect them into your resulting data structure. There is no utility method available that can do this automatically for you, but it is fairly easy to do it yourself.
Stream API
Streams are a very good candidate for this. Just stream the outer list, convert the inner lists and then use toArray as provided by Stream.
String[][] result = outer.stream() // Stream<List<String>>
.map(inner -> inner.toArray(String[]::new)) // Stream<String[]>
.toArray(String[][]::new);
Traditional loop
You can follow the exact same idea also with a more traditional manual approach where you setup your target outer array, loop over the inner lists, convert them and collect them into your array.
String[][] result = new String[outer.size()];
int i = 0;
for (List<String> inner : outer) {
result[i] = inner.toArray(String[]::new);
i++;
}

Java array vs ArrayList vs List [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Im trying to understand the relationship between array, ArrayList, and List.
Say I wanted to remove duplicates by converting an array into an ArrayList then into a HashSet, then returned to an array.
int[] start = {1,2,3,4,5};
....
....
....
int[] result = .....
How would that work?
Array is a fixed length data structure. It is a continuous block of memory. Let say you have an array at x3000 with a length of 2. An array stay at x3000 and x3001. Remember, this is oversimplifying the concept, as element size and size per memory location will certainly affect the position of array's elements (not always end at x3001).
List is an abstract data type (ADT), the notable difference between list and array is list has no fixed length. There can be more differences but it may vary from case to case.
ArrayList is a ADT list, but implemented using array. It's like when you do problems that require constructing stack, queue, etc using array.
int[] array = {1, 2, 3, 4, 5};
for(int i : array) {
System.out.print(i+", ");
}
System.out.println();
ArrayList myArrayList = new ArrayList();
for(int num : array) {
myArrayList.add(num);
}
System.out.println(myArrayList);
HashSet<Integer> myHashSet = new HashSet<Integer>();
for(int i = 0;i<myArrayList.size();i++) {
myHashSet.add((Integer) myArrayList.get(i));
}
System.out.println(myHashSet);
This is an example of a normal int array converted to an ArrayList converted to a HashSet.
the relationship between array, ArrayList, and List.
An array is created with the [] and {} notation you showed in your question. It's not dynamically allocated.
A List is an interface, which is just a guide to what methods its implementations must respond to.
An ArrayList is an implementation of a List.

How to find the median of n values Without using Arrays (or list or any other collection/ function that uses arrays/list)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Scenario:
The user is supposed to enter N (the number of values)
followed by N values.
How can I output the median?
Without Array, without List, or any other Collection.
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Number of numbers: ");
int N = scanner.nextInt();
System.out.printf("Enter the %d numbers: ", N);
double median = IntStream.range(0, N)
.mapToDouble(i -> scanner.nextDouble())
.sorted()
.skip((N-1)/2)
.limit(2-N%2)
.average()
.getAsDouble();
System.out.printf("The median is %f%n", median);
}
(Pay no attention to that man behind the .sorted() curtain.)
I suggest that you hand program a binary tree. You probably need to allow duplicates, to Java’s built in TreeSet won’t do. It may also be that you can find a suitable tree implementation somewhere on the net. The tree should be sorted. See Binary search tree on Wikipedia for more inspiration.
Your main program will read your numbers one by one and insert them into your tree. After that, it will query the tree for the middle element, or two middle elements if N is even.
You don’t need any array to implement your tree. For finding the ith element, the tree will perform an inorder traversal counting the elements encountered and returning the ith element.
You definitely need some storage for at least N/2 places. There's no way around that.
EDITED after OP's coment:
Get some good course on programming, esp. data structures. You can't rely on Stackoverflow for all your developer career ;-). Having said that, let's give you a starting point: I'd use an ArrayList here:
int n = ...; // get N from the user;
List<Double> list = new ArrayList<Double>();
for (int i=0; i<n; i++) {
double element = ...; // get element from the user;
list.add(element);
}
// Have the Java library sort the list for you
Collections.sort(list);
// now pick/compute the median from the sorted list
// I'll leave that up to you..

How to iterate over items of list and delete duplicated ones while remain the original order? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Note: This question is for my assignment. So there are some rules which might seem to be not normal.
I just realized my question before doesn't make sense. So I edited it.
Assume that I have a list containing integers [1,2,3,4,1,2,1,5]
By using an iterator, how can I remove duplicated items while keeping the order of items undisrupted?
The expected result for above list should be [1,2,3,4,5]
And contain() method is not allowed to use.
What I currently came up with is the same as what Manash Ranjan Dakua answered in this question
How do I remove repeated elements from ArrayList?
public static void main(String[] args){
ArrayList<Object> al = new ArrayList<Object>();
al.add("abc");
al.add('a');
al.add('b');
al.add('a');
al.add("abc");
al.add(10.3);
al.add('c');
al.add(10);
al.add("abc");
al.add(10);
System.out.println("Before Duplicate Remove:"+al);
for(int i=0;i<al.size();i++){
for(int j=i+1;j<al.size();j++){
if(al.get(i).equals(al.get(j))){
al.remove(j);
j--;
}
}
}
System.out.println("After Removing duplicate:"+al);
}
But if I wish to use Iterator instead of for loops here? How can I achieve that(remove duplicated items while keeping order unchanged)?
If the question is not clear enough or too vague. Pls point out! I'll try to rephrase it.
Thanks for help!
You don't need to use Iterator to achieve that. A simple way is using LinkedHashSet which allows to contain unique elements only like HashSet (No Duplicates) and maintains insertion order.
Example:
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,1,2,1,5));
Set<Integer> set = new LinkedHashSet<>();
set.addAll(list);
// or as suggested by assylias, Set<Integer> set = new LinkedHashSet<>(list);
System.out.println(list);
System.out.println(set);
Output:
[1, 2, 3, 4, 1, 2, 1, 5]
[1, 2, 3, 4, 5]
You can simply call .next() again which will allow you to move on to the next element in the array. However if you want to get a new iterator for the rest of the elements, it would be best for you to use .next() through the rest of the list you have, adding each element to a new data structure and then call .iterator() on that new data structure.

Add Elements to ArrayList<ArrayList<String>> [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an ArrayList of ArrayList. How can I add an element to the list in specific position?
Example:
ArrayList<ArrayList<String>>=new ArrayList<>(list,list2,.....,listn);
I want to add an element to list2 for example.
You would get the second element and add to it: -
list.get(1).add(myString);
Remember it's 0 based though.
You need to get from your outer ArrayList your desired inner ArrayList first like
outerList.get(1); //this will return list2
then you can add to that inner arrayList some values like
outerList.get(1).add("your value"); //this will add element to list2
Assuming you named your list 'list':
list.get(1).add("x");
Where x is whatever you want to add to the second list.
Well, if you have list2, it's easy. You do :
list2.add("Moon");
If you only have the big list, which we shall call bigList, you do :
bigList.get(1).add("Moon");
Indexes in Java start at 0.
ArrayList<ArrayList<String>> myList=new ArrayList<>();
ArrayList<String> list1=new ArrayList<>();
ArrayList<String> list2=new ArrayList<>();
ArrayList<String> list3=new ArrayList<>();
list1.add("a") ; // add elements for list1
list2.add("b"); // add elements for list2
list3.add("c"); // add elements for list3
myList.add(list1); // add elements for myList
myList.add(list2);
myList.add(list3);
//Now I want to add new value for list2
myList.get(1).add("bb"); // indexes start with zero same as Arrays

Categories

Resources