• Post Reply Bookmark Topic Watch Topic
  • New Topic

Manipulations with array list.  RSS feed

 
Ibragim Gapuraev
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone. I need to write a code fragment to determine the number of the elements held
in Array List "list" which are greater than half the maximum value.
Here I have found maximum value:

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(new Integer("3"));
list.add(new Integer("1"));
list.add(new Integer("34"));
list.add(new Integer("32"));
list.add(new Integer("56"));

Object obj = Collections.max(list);
System.out.println(obj);

Any ideas?

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you know how to iterate over the elements of an ArrayList and how to get elements from an ArrayList? Once you know this, it should be pretty straightforward to do what you want. Have a look at the Collections tutorial to learn how to work with collection classes such as ArrayList.

By the way, your code is a bit verbose. This works just as well:
 
Randall Fairman
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Unless there's some natural way to impose a sort order on the data as it's inserted, you really don't have much choice. You'll have to visit every entry as compare to the largest value seen so far.
 
Mittal Vishal
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ibragim,
following piece of code will help

Integer maxValue = Collections.max(list);
Integer halfMax = maxValue / 2;
for (Integer value : list)
{
if (value > halfMax)
{
System.out.println(value);
}
}
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Randall Fairman wrote: . . . don't have much choice. You'll have to visit every entry as compare to the largest value seen so far.
Agree. That is the way a List is designed. It maintains insertion order as a default. If Ibragim Gapuraev wants a sorted collection, he should think of something like a tree set.

And welcome to the Ranch
 
Ibragim Gapuraev
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!