搜索词>>ArrayList 耗时0.2380
  • java编程基础数组ArrayList使用详解

    java编程基础数组ArrayList使用详解<p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">Java编程基础中的ArrayList用于存储动态大小的元素集合。与大小固定的数组相反,ArrayList会在添加新元素时自动增大其大小。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">ArrayList是Java集合框架的一部分,它实现了Java的<code>List</code>接口。<img alt="list" class="img-thumbnail" src="/assist/images/blog/3a58de20c693483dba6ea4d6a42b7e2a.jpg" /></span></span></span><br /> <br />  </p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下几点需要注意Java中的ArrayList -</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">ArrayList是一个可调整大小的数组,也称为动态数组。它的尺寸越来越大,以适应新的元素,并在元素被移除时缩小尺寸。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">ArrayList内部使用数组来存储元素。就像数组一样,它允许您通过索引来检索元素。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">Java ArrayList允许重复值和空值。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">Java ArrayList是一个有序的集合。它维护元素的插入顺序。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">您不能创建原始类型,如一个ArrayList <code>int</code>,<code>chat</code>等你需要用盒装的类型,如<code>Integer</code>,<code>Character</code>,<code>Boolean</code>等。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">Java ArrayList不同步。如果多个线程同时尝试修改ArrayList,那么最终结果将是非确定性的。如果多个线程要修改它,你必须显式同步对ArrayList的访问。</p> </li> </ul> <h2 style="margin-left:0px; margin-right:0px; text-align:start">创建一个ArrayList并添加新的元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li>如何使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>ArrayList()</code></a>构造函数创建ArrayList 。</li> <li>使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-E-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>add()</code></a>方法向ArrayList添加新元素。</li> </ul> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class CreateArrayListExample { public static void main(String[] args) { // Creating an ArrayList of String List<String> animals = new ArrayList<>(); // Adding new elements to the ArrayList animals.add("Lion"); animals.add("Tiger"); animals.add("Cat"); animals.add("Dog"); System.out.println(animals); // Adding an element at a particular index in an ArrayList animals.add(2, "Elephant"); System.out.println(animals); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><br /> <span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出</span></span></span></p> <pre> <code class="language-html">[Lion, Tiger, Cat, Dog] [Lion, Tiger, Elephant, Cat, Dog]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">从另一个集合创建一个ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">如何使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>ArrayList(Collection c)</code></a>构造函数从另一个ArrayList创建一个ArrayList 。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#addAll-java.util.Collection-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>addAll()</code></a>方法将现有ArrayList中的所有元素添加到新的ArrayList中。</p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class CreateArrayListFromCollectionExample { public static void main(String[] args) { List<Integer> firstFivePrimeNumbers = new ArrayList<>(); firstFivePrimeNumbers.add(2); firstFivePrimeNumbers.add(3); firstFivePrimeNumbers.add(5); firstFivePrimeNumbers.add(7); firstFivePrimeNumbers.add(11); // Creating an ArrayList from another collection List<Integer> firstTenPrimeNumbers = new ArrayList<>(firstFivePrimeNumbers); List<Integer> nextFivePrimeNumbers = new ArrayList<>(); nextFivePrimeNumbers.add(13); nextFivePrimeNumbers.add(17); nextFivePrimeNumbers.add(19); nextFivePrimeNumbers.add(23); nextFivePrimeNumbers.add(29); // Adding an entire collection to an ArrayList firstTenPrimeNumbers.addAll(nextFivePrimeNumbers); System.out.println(firstTenPrimeNumbers); } }</code></pre> </li> </ul> <p style="margin-left:0px; margin-right:0px; text-align:start"><br /> <span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">访问ArrayList中的元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>isEmpty()</code></a>方法检查ArrayList是否为空。</li> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#size--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>size()</code></a>方法找到ArrayList的大小。</li> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#get-int-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>get()</code></a>方法访问ArrayList中特定索引处的元素。</li> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#set-int-E-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>set()</code></a>方法修改ArrayList中特定索引处的元素。</li> </ul> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class AccessElementsFromArrayListExample { public static void main(String[] args) { List<String> topCompanies = new ArrayList<>(); // Check is an ArrayList is empty System.out.println("Is the topCompanies list empty? : " + topCompanies.isEmpty()); topCompanies.add("Google"); topCompanies.add("Apple"); topCompanies.add("Microsoft"); topCompanies.add("Amazon"); topCompanies.add("Facebook"); // Find the size of an ArrayList System.out.println("Here are the top " + topCompanies.size() + " companies in the world"); System.out.println(topCompanies); // Retrieve the element at a given index String bestCompany = topCompanies.get(0); String secondBestCompany = topCompanies.get(1); String lastCompany = topCompanies.get(topCompanies.size() - 1); System.out.println("Best Company: " + bestCompany); System.out.println("Second Best Company: " + secondBestCompany); System.out.println("Last Company in the list: " + lastCompany); // Modify the element at a given index topCompanies.set(4, "Walmart"); System.out.println("Modified top companies list: " + topCompanies); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Is the topCompanies list empty? : true Here are the top 5 companies in the world [Google, Apple, Microsoft, Amazon, Facebook] Best Company: Google Second Best Company: Apple Last Company in the list: Facebook Modified top companies list: [Google, Apple, Microsoft, Amazon, Walmart]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">从ArrayList中移除元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ol style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">如何删除ArrayList |中给定索引处的元素 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">delete</a><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-int-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">(int索引)</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何从ArrayList |中删除元素 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">delete(Object o)</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何从给定集合中存在的ArrayList中移除所有元素| <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">delete</a>All<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#removeAll-java.util.Collection-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何删除所有匹配给定谓词|的元素 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#removeIf-java.util.function.Predicate-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">removeIf()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何清除ArrayList | <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#clear--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">clear()</a></p> </li> </ol> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class RemoveElementsFromArrayListExample { public static void main(String[] args) { List<String> programmingLanguages = new ArrayList<>(); programmingLanguages.add("C"); programmingLanguages.add("C++"); programmingLanguages.add("Java"); programmingLanguages.add("Kotlin"); programmingLanguages.add("Python"); programmingLanguages.add("Perl"); programmingLanguages.add("Ruby"); System.out.println("Initial List: " + programmingLanguages); // Remove the element at index `5` programmingLanguages.remove(5); System.out.println("After remove(5): " + programmingLanguages); // Remove the element "Kotlin" (The remove() method returns false if the element does not exist in the ArrayList) boolean isRemoved = programmingLanguages.remove("Kotlin"); System.out.println("After remove(\"Kotlin\"): " + programmingLanguages); // Remove all the elements belonging to the collection scriptingLanguages List<String> scriptingLanguages = new ArrayList<>(); scriptingLanguages.add("Python"); scriptingLanguages.add("Ruby"); scriptingLanguages.add("Perl"); programmingLanguages.removeAll(scriptingLanguages); System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages); // Remove all the elements that satisfy the given predicate programmingLanguages.removeIf(new Predicate<String>() { @Override public boolean test(String s) { return s.startsWith("C"); } }); /* The above removeIf() call can also be written using lambda expression like this - programmingLanguages.removeIf(s -> s.startsWith("C")) */ System.out.println("After Removing all elements that start with \"C\": " + programmingLanguages); // Remove all elements from the ArrayList programmingLanguages.clear(); System.out.println("After clear(): " + programmingLanguages); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby] After remove(5): [C, C++, Java, Kotlin, Python, Ruby] After remove("Kotlin"): [C, C++, Java, Python, Ruby] After removeAll(scriptingLanguages): [C, C++, Java] After Removing all elements that start with "C": [Java] After clear(): []</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">迭代ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下示例显示如何使用迭代遍历ArrayList</span></span></span></p> <ol style="margin-left:30px; margin-right:0px"> <li>Java 8 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#forEach-java.util.function.Consumer-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>forEach</code></a>循环。</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#iterator--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>iterator()</code></a>。</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#iterator--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>iterator()</code></a>和Java 8 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">forEachRemaining()</a>方法。</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#listIterator-int-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>listIterator()</code></a>。</li> <li>每个循环都很简单。</li> <li>用索引循环。</li> </ol> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IterateOverArrayListExample { public static void main(String[] args) { List<String> tvShows = new ArrayList<>(); tvShows.add("Breaking Bad"); tvShows.add("Game Of Thrones"); tvShows.add("Friends"); tvShows.add("Prison break"); System.out.println("=== Iterate using Java 8 forEach loop ==="); tvShows.forEach(tvShow -> { System.out.println(tvShow); }); System.out.println("\n=== Iterate using an iterator() ==="); Iterator<String> tvShowIterator = tvShows.iterator(); while (tvShowIterator.hasNext()) { String tvShow = tvShowIterator.next(); System.out.println(tvShow); } System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ==="); tvShowIterator = tvShows.iterator(); tvShowIterator.forEachRemaining(tvShow -> { System.out.println(tvShow); }); System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ==="); // Here, we start from the end of the list and traverse backwards. ListIterator<String> tvShowListIterator = tvShows.listIterator(tvShows.size()); while (tvShowListIterator.hasPrevious()) { String tvShow = tvShowListIterator.previous(); System.out.println(tvShow); } System.out.println("\n=== Iterate using simple for-each loop ==="); for(String tvShow: tvShows) { System.out.println(tvShow); } System.out.println("\n=== Iterate using for loop with index ==="); for(int i = 0; i < tvShows.size(); i++) { System.out.println(tvShows.get(i)); } } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">=== Iterate using Java 8 forEach loop === Breaking Bad Game Of Thrones Friends Prison break === Iterate using an iterator() === Breaking Bad Game Of Thrones Friends Prison break === Iterate using an iterator() and Java 8 forEachRemaining() method === Breaking Bad Game Of Thrones Friends Prison break === Iterate using a listIterator() to traverse in both directions === Prison break Friends Game Of Thrones Breaking Bad === Iterate using simple for-each loop === Breaking Bad Game Of Thrones Friends Prison break === Iterate using for loop with index === Breaking Bad Game Of Thrones Friends Prison break</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">在遍历期间需要修改ArrayList时,<code>iterator()</code>和<code>listIterator()</code>方法很有用。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">考虑下面的例子,在<code>iterator.remove()</code>遍历它的时候我们使用方法从ArrayList中移除元素-</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListIteratorRemoveExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(13); numbers.add(18); numbers.add(25); numbers.add(40); Iterator<Integer> numbersIterator = numbers.iterator(); while (numbersIterator.hasNext()) { Integer num = numbersIterator.next(); if(num % 2 != 0) { numbersIterator.remove(); } } System.out.println(numbers); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">[18, 40]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">在ArrayList中搜索元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">下面的例子显示了如何:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">检查ArrayList是否包含给定的元素|  <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#contains-java.lang.Object-" rel="external nofollow" target="_blank">contains</a><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#contains-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">查找ArrayList |中第一次出现元素的索引 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-" rel="external nofollow" target="_blank">indexOf</a><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">查找ArrayList |中最后一次出现元素的索引 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#lastIndexOf-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">lastIndexOf()</a></p> </li> </ul> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class SearchElementsInArrayListExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("John"); names.add("Alice"); names.add("Bob"); names.add("Steve"); names.add("John"); names.add("Steve"); names.add("Maria"); // Check if an ArrayList contains a given element System.out.println("Does names array contain \"Bob\"? : " + names.contains("Bob")); // Find the index of first occurrence of an element in an ArrayList System.out.println("indexOf \"Steve\": " + names.indexOf("Steve")); System.out.println("indexOf \"Mark\": " + names.indexOf("Mark")); // Find the index of the last occurrence of an element in an ArrayList System.out.println("lastIndexOf \"John\" : " + names.lastIndexOf("John")); System.out.println("lastIndexOf \"Bill\" : " + names.lastIndexOf("Bill")); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Does names array contain "Bob"? : true indexOf "Steve": 3 indexOf "Mark": -1 lastIndexOf "John" : 4 lastIndexOf "Bill" : -1</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">用户定义对象的ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">由于ArrayList支持泛型,因此可以创建<strong>任何</strong>类型的ArrayList 。它可以是简单的类型,如<code>Integer</code>,<code>String</code>,<code>Double</code>或复杂类型等的ArrayLists的ArrayList,或包含HashMap的ArrayList或任何用户定义的对象的ArrayList。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">在以下示例中,您将学习如何创建用户定义对象的ArrayList。</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class ArrayListUserDefinedObjectExample { public static void main(String[] args) { List<User> users = new ArrayList<>(); users.add(new User("Rajeev", 25)); users.add(new User("John", 34)); users.add(new User("Steve", 29)); users.forEach(user -> { System.out.println("Name : " + user.getName() + ", Age : " + user.getAge()); }); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Name : Rajeev, Age : 25 Name : John, Age : 34 Name : Steve, Age : 29</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">排序ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">对ArrayList进行排序是您在程序中遇到的一个非常常见的任务。在本节中,我会告诉你如何 -</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li>使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>Collections.sort()</code></a>方法对ArrayList进行排序。</li> <li>使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#sort-java.util.Comparator-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>ArrayList.sort()</code></a>方法对ArrayList进行排序。</li> <li>用自定义比较器对用户定义对象的ArrayList进行排序。</li> </ul> <h4 style="margin-left:0px; margin-right:0px; text-align:start">1.使用Collections.sort()方法对ArrayList进行排序</h4> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayListCollectionsSortExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(13); numbers.add(7); numbers.add(18); numbers.add(5); numbers.add(2); System.out.println("Before : " + numbers); // Sorting an ArrayList using Collections.sort() method Collections.sort(numbers); System.out.println("After : " + numbers); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Before : [13, 7, 18, 5, 2] After : [2, 5, 7, 13, 18]</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start">2.使用ArrayList.sort()方法对ArrayList排序<br />  </p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ArrayListSortExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Lisa"); names.add("Jennifer"); names.add("Mark"); names.add("David"); System.out.println("Names : " + names); // Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method. names.sort(new Comparator<String>() { @Override public int compare(String name1, String name2) { return name1.compareTo(name2); } }); // The above `sort()` method call can also be written simply using lambda expressions names.sort((name1, name2) -> name1.compareTo(name2)); // Following is an even more concise solution names.sort(Comparator.naturalOrder()); System.out.println("Sorted Names : " + names); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Names : [Lisa, Jennifer, Mark, David] Sorted Names : [David, Jennifer, Lisa, Mark]</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start">3.使用自定义比较器对对象的ArrayList进行排序<br />  </p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Person { private String name; private Integer age; public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public class ArrayListObjectSortExample { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Sachin", 47)); people.add(new Person("Chris", 34)); people.add(new Person("Rajeev", 25)); people.add(new Person("David", 31)); System.out.println("Person List : " + people); // Sort People by their Age people.sort((person1, person2) -> { return person1.getAge() - person2.getAge(); }); // A more concise way of writing the above sorting function people.sort(Comparator.comparingInt(Person::getAge)); System.out.println("Sorted Person List by Age : " + people); // You can also sort using Collections.sort() method by passing the custom Comparator Collections.sort(people, Comparator.comparing(Person::getName)); System.out.println("Sorted Person List by Name : " + people); } }</code></pre> 输出: <pre> <code class="language-html">Person List : [{name='Sachin', age=47}, {name='Chris', age=34}, {name='Rajeev', age=25}, {name='David', age=31}] Sorted Person List by Age : [{name='Rajeev', age=25}, {name='David', age=31}, {name='Chris', age=34}, {name='Sachin', age=47}] Sorted Person List by Name : [{name='Chris', age=34}, {name='David', age=31}, {name='Rajeev', age=25}, {name='Sachin', age=47}]</code></pre>   <h2 style="margin-left:0px; margin-right:0px; text-align:start">同步对ArrayList的访问</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">ArrayList类不同步。如果多个线程同时尝试修改一个ArrayList,那么最终的结果变得不确定,因为一个线程可能会覆盖另一个线程所做的更改。</span></span></span></p> <h4 style="margin-left:0px; margin-right:0px; text-align:start">示例演示ArrayList在多线程环境中的不可预知行为</h4> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下示例显示了当多个线程同时尝试修改ArrayList时发生的情况。</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class UnsafeArrayListExample { public static void main(String[] args) throws InterruptedException { List<Integer> unsafeArrayList = new ArrayList<>(); unsafeArrayList.add(1); unsafeArrayList.add(2); unsafeArrayList.add(3); // Create a thread pool of size 10 ExecutorService executorService = Executors.newFixedThreadPool(10); // Create a Runnable task that increments the each element of the ArrayList by one Runnable task = () -> { incrementArrayList(unsafeArrayList); }; // Submit the task to the executor service 100 times. // All the tasks will modify the ArrayList concurrently for(int i = 0; i < 100; i++) { executorService.submit(task); } executorService.shutdown(); executorService.awaitTermination(60, TimeUnit.SECONDS); System.out.println(unsafeArrayList); } // Increment all the values in the ArrayList by one private static void incrementArrayList(List<Integer> unsafeArrayList) { for(int i = 0; i < unsafeArrayList.size(); i++) { Integer value = unsafeArrayList.get(i); unsafeArrayList.set(i, value + 1); } } }</code></pre> 上述程序的最终输出应该相等,<code>[101, 102, 103]</code>因为我们将ArrayList中的值增加了100次。但是如果你运行这个程序,它会在每次运行时产生不同的输出 -<br /> 输出: <pre> <code class="language-html">[96, 96, 98]</code></pre>   <h4 style="margin-left:0px; margin-right:0px; text-align:start">演示如何将并发修改同步到ArrayList的示例</h4> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">好吧!现在让我们看看我们如何<code>ArrayList</code>在多线程环境中同步访问。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下示例显示了上一个示例的同步版本。与以前的程序不同,该程序的输出是确定性的,并且始终是相同的。</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SynchronizedArrayListExample { public static void main(String[] args) throws InterruptedException { List<Integer> safeArrayList = Collections.synchronizedList(new ArrayList<>()); safeArrayList.add(1); safeArrayList.add(2); safeArrayList.add(3); // Create a thread pool of size 10 ExecutorService executorService = Executors.newFixedThreadPool(10); // Create a Runnable task that increments the each element of the ArrayList by one Runnable task = () -> { incrementArrayList(safeArrayList); }; // Submit the task to the executor service 100 times. // All the tasks will modify the ArrayList concurrently for(int i = 0; i < 100; i++) { executorService.submit(task); } executorService.shutdown(); executorService.awaitTermination(60, TimeUnit.SECONDS); System.out.println(safeArrayList); } // Increment all the values in the ArrayList by one private static void incrementArrayList(List<Integer> safeArrayList) { synchronized (safeArrayList) { for (int i = 0; i < safeArrayList.size(); i++) { Integer value = safeArrayList.get(i); safeArrayList.set(i, value + 1); } } } }</code></pre> 输出: <pre> <code class="language-html">[101, 102, 103]</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以上示例使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedList-java.util.List-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>Collections.synchronizedList()</code></a>方法来获取ArrayList的同步视图。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">而且,对<code>incrementArrayList()</code>方法内的ArrayList的修改被封装在一个<code>synchronized</code>块中。这确保了两个线程不能同时增加ArrayList元素。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff"><em><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>CopyOnWriteArrayList</code></a>如果你需要线程安全,你也可以使用。它是ArrayList类的线程安全版本。它通过创建ArrayList的新副本来实现所有的变异操作。</em></span></span></span></p>
  • java基础ArrayList与LinkedList的区别以及使用场景

    本文组要摘录了网上各位大佬的总结。作为笔记搜录。尽量详细的讲解ArrayList与LinkedList的区别以及在何时选择那个用。<h2>一.ArrayList与LinkedList的区别</h2>  说法一: <ol> <li>因为Array是基于索引(index)的数据结构,它使用索引在数组中搜索和读取数据是很快的。Array获取数据的时间复杂度是O(1),但是要新增或者删除数据却是开销很大的,因为这需要重排数组中的所有数据。</li> <li>相对于ArrayList,LinkedList插入是更快的。因为LinkedList不像ArrayList一样,不需要改变数组的大小,也不需要在数组装满的时候要将所有的数据重新装入一个新的数组,这是ArrayList最坏的一种情况,时间复杂度是O(n),而LinkedList中插入或删除的时间复杂度仅为O(1)。ArrayList在插入或sh数据删除需要更新索引(除了插入数组的尾部)。</li> <li>LinkedList需要更多的内存,因为ArrayList的每个索引的位置是实际的数据,而LinkedList中的每个节点中存储的是实际的数据和前后节点的位置</li> </ol> 说法二: <ol> <li>ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。 </li> <li>对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针。 </li> <li>对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。 </li> </ol> 以上说法均为正确。 <h2>二.ArrayList与LinkedList的使用场景</h2> LinkedList: <ul> <li> 你的应用不会随机访问数据。因为如果你需要LinkedList中的第n个元素的时候,你需要从第一个元素顺序数到第n个数据,然后读取数据。</li> <li> 你的应用更多的插入和删除元素,更少的读取数据。因为插入和删除元素不涉及重排数据,所以它要比ArrayList要快。</li> </ul> ArrayList: <ul> <li>你的应用需要随机访问数据,基本不会在list中插入或者删除元素</li> </ul>
  • Java 8 Stream concat() 合并多个流

    本文主要讲解通过使用 Stream.concat() 方法 去合并两个stream,新的stream由原来的两个stream所有元素组成(相同元素会覆盖)本文主要讲解通过使用 Stream.concat() 方法 去合并两个stream,新的stream由原来的两个stream所有元素组成(相同元素会覆盖)。1.Stream concat()方法基本介绍static <T> Stream<T> concat(Stream<? extends T> firstStream, Stream<? extends T> secondStream)此方法创建一个延迟连接的流,其元素是firstStream的所有元素,后跟secondStream的所有元素。如果两个输入流都是有序的,则对所得到的流进行排序。如果任一输入流是并行的,则得到的流是平行的。关闭结果流时,将调用两个输入流的关闭处理程序。2.Stream concat()合并两个stream 下面用两个数字类型的stream进行合并。public class Main { public static void main(String[] args) { Stream<Integer> firstStream = Stream.of(1, 2, 3); Stream<Integer> secondStream = Stream.of(4, 5, 6); Stream<Integer> resultingStream = Stream.concat(firstStream, secondStream); System.out.println( resultingStream.collect(Collectors.toList()) ); } } 程序运行输出:$title(Console) [1, 2, 3, 4, 5, 6]3.合并多个流(Streams) 下面使用4个数字的stream作为演示数据。import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Stream.*; public class Main { public static void main(String[] args) { Stream<Integer> first = Stream.of(1, 2); Stream<Integer> second = Stream.of(3,4); Stream<Integer> third = Stream.of(5, 6); Stream<Integer> fourth = Stream.of(7,8); Stream<Integer> resultingStream = Stream.concat(first, concat(second, concat(third, fourth))); System.out.println( resultingStream.collect(Collectors.toList()) ); } } 程序输出:$title(Console) [1, 2, 3, 4, 5, 6, 7, 8]4.合并stream并保留唯一性4.1数字和字符串 在合并两个流  并且保证数据唯一性,import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Stream<Integer> firstStream = Stream.of(1, 2, 3, 4, 5, 6); Stream<Integer> secondStream = Stream.of(4, 5, 6, 7, 8, 9); Stream<Integer> resultingStream = Stream.concat(firstStream, secondStream) .distinct(); System.out.println( resultingStream.collect(Collectors.toList()) ); } } 输出结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]4.2自定义对象对比 在合并自定义对象流的情况下,我们可以在流迭代期间删除重复的元素。 我们可以使用对象属性示例为java流创建的distinctByKey()函数 import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Stream<Employee> stream1 = getEmployeeListOne().stream(); Stream<Employee> stream2 = getEmployeeListTwo().stream(); Stream<Employee> resultingStream = Stream.concat(stream1, stream2) .filter(distinctByKey(Employee::getFirstName)); System.out.println( resultingStream.collect(Collectors.toList()) ); } public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } private static ArrayList<Employee> getEmployeeListOne() { ArrayList<Employee> list = new ArrayList<>(); list.add( new Employee(1l, "Lokesh", "Gupta") ); list.add( new Employee(5l, "Brian", "Piper") ); list.add( new Employee(7l, "Charles", "Piper") ); list.add( new Employee(6l, "David", "Beckham") ); return list; } private static ArrayList<Employee> getEmployeeListTwo() { ArrayList<Employee> list = new ArrayList<>(); list.add( new Employee(2l, "Lokesh", "Gupta") ); list.add( new Employee(4l, "Brian", "Piper") ); list.add( new Employee(3l, "David", "Beckham") ); return list; } } 输出结果 Employee [id=1, firstName=Lokesh, lastName=Gupta], Employee [id=5, firstName=Brian, lastName=Piper], Employee [id=7, firstName=Charles, lastName=Piper], Employee [id=6, firstName=David, lastName=Beckham]]把你的疑问留在留言板我会不定期解答。
  • java 8 stream List去重/集合去重

    简介本博文主要讲解在Java 8中 如何通过stream流的方式去重简介本博文主要讲解在Java 8中 如何通过stream流的方式去重。List<String>通过stream去重List unique = list.stream().distinct().collect(Collectors.toList()); List<String>通过stream去重是非常简单的。就上面的一句代码搞定List<对象>通过stream根据集合对象的某个属性或者某些属性去重// Person 对象 public class Person { private String id; private String name; private String sex; <!--省略 get set--> } 根据name去重// 根据name去重 List<Person> unique = persons.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new) ); 根据name sex两个属性去重List<Person> unique = persons.stream().collect( Collectors. collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new) );
  • Java8中的流Stream

    jdk8新特性流的使用<h2><strong>java 8中的流(Stream)</strong></h2> 之前因为工作原因经常需要对查询的数据库的数据集合进行筛选或者排序之类的操作,今天看了下jdk8特性,根据stream可以自动满足这些操作。 <p>流是Java API的新成员,它允许你以声明性方式处理数据集合(通过查询语句来表达,而不是临时编写一个实现)</p> <p>Java 8中的Stream API可以让你写出这样的代码:</p> <p> 声明性——更简洁,更易读</p> <p> 可复合——更灵活</p> <p> 可并行——性能更好<br /> <br /> 首先看一下使用流和不使用流的区别,需求: 把集合中年龄小于等于20的人的名字取出来并排序<br /> 不使用流:</p> <pre> <code class="language-java">//传统JDK排序抽取数据 // 把集合中年龄小于等于20的人的名字取出来并排序 // 第一步:取年龄 <= 20的用户 List<User> tmpList = new ArrayList<>(); for (User u : list) { if (u.getAge() <= 20){ tmpList.add(u); } } // 第二步:排序 Collections.sort(tmpList, new Comparator<User>() { public int compare(User u1, User u2) { return u1.getName().compareTo(u2.getName()); } }); // 第三步 List<String> userNames = new ArrayList<>(); for(User u : tmpList){ userNames.add(u.getName()); }</code></pre> <p>jdk8流新特性<br />  </p> <pre> <code class="language-java">//JDK流新特性 //为了利用多核架构并行执行这段代码,只需要把stream()换成parallelStream(): List<String> userNames = list.stream() .filter(userJdk8 -> userJdk8.getAge() <= 20) .sorted(Comparator.comparing(User::getName)) .map(User::getName) .collect(Collectors.toList()); System.out.println(userNames.toString());</code></pre> <p> </p> <h2><strong>流与集合的区别:</strong></h2> <p>集合与流之间的差异就在于什么时候进行计算。集合是一个内存中的数据结构,它包含数据结构中目前所有的值——集合中的每个元素都得先算出来才能添加到集合中。(你可以往集合里加东西或者删东西,但是不管什么时候,集合中的每个元素都是放在内存里的,元素都得先算出来才能成为集合的一部分。)相比之下,流则是在概念上固定的数据结构(你不能添加或删除元素),其元素则是按需计算的。 从另一个角度来说,流就像是一个延迟创建的集合:只有在消费者要求的时候才会计算值。以质数为例,要是想创建一个包含所有质数的集合,那这个程序算起来就没完没了了,因为总有新的质数要算,然后把它加到集合里面。而流的话,仅仅从流中提取需要的值,而这些值——在用户看不见的地方,只会按需生成。<br /> 流只能被消费一次,如果被消费多次,则会抛出异常:</p> <pre> <code>java.lang.IllegalStateException: stream has already been operated upon or closed</code></pre> <p>如下代码所示: 这段代码的意思是遍历 lists 集合</p> <pre> <code class="language-java">List<String> lists = Arrays.asList("java8","lambda","stream"); Stream<String> stringStream = lists.stream(); Consumer<String> consumer = (x) -> System.out.println(x); stringStream.forEach(consumer); //stream has already been operated upon or closed stringStream.forEach(consumer);</code></pre> <p>之前测试类完整代码,更多stream参考<a rel="external nofollow" target="_blank" href="https://docs.oracle.com/javase/8/docs/api/">jdk8API在线文档</a>:<br />  </p> <pre> <code class="language-java">package com.yeyue; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * @ClassName: JDK8Test * @Description: jdk8流的作用 此例是把集合中年龄小于等于20的人的名字取出来并排序 * @author: xiaoboLi * @date: 2017/11/22 14:32 * @Copyright: 2017 All rights reserved. */ public class JDK8Test { public static void main(String[] args) { List<User> list = new ArrayList<>(); User user = new User(11, "zhangsan", 1); list.add(user); user = new User(19, "lisi", 1); list.add(user); user = new User(10, "wanger", 0); list.add(user); user = new User(7, "wangmazi", 0); list.add(user); user = new User(25, "hanmeimei", 0); list.add(user); user = new User(30, "lilei", 0); list.add(user); //传统JDK排序抽取数据 // 把集合中年龄小于等于20的人的名字取出来并排序 // 第一步:取年龄 <= 20的用户 List<User> tmpList = new ArrayList<>(); for (User u : list) { if (u.getAge() <= 20){ tmpList.add(u); } } // 第二步:排序 Collections.sort(tmpList, new Comparator<User>() { public int compare(User u1, User u2) { return u1.getName().compareTo(u2.getName()); } }); // 第三步 List<String> userNames = new ArrayList<>(); for(User u : tmpList){ userNames.add(u.getName()); } System.out.println(userNames.toString()); //JDK流新特性 //为了利用多核架构并行执行这段代码,只需要把stream()换成parallelStream(): userNames = list.stream() .filter(userJdk8 -> userJdk8.getAge() <= 20) .sorted(Comparator.comparing(User::getName)) .map(User::getName) .collect(Collectors.toList()); System.out.println(userNames.toString()); //取小于20岁的人员信息并且根据年龄升序排序 List<User> aList = list.stream() .filter(userJdk8 -> userJdk8.getAge() <= 20) .sorted(Comparator.comparing(User::getAge)) .collect(Collectors.toList()); for (User u : aList) { System.out.println(u.getName()); } } } class User { private int age; private String name; private int sex; public User(int age, String name, int sex) { this.age = age; this.name = name; this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } }</code></pre>
  • Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ

    Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ<h2>一.项目结构<br /> 本教程创建的应用程序结构如下:</h2> <strong><img alt="Spring-Boot-Jersey-Project-Structure" class="img-thumbnail" src="/assist/images/blog/034cb03ceabf43fea761e136b7e97a9b.png" /></strong> <h2>二.从Spring Initializr创建Spring boot应用程序</h2> <strong>1.访问Spring Initializr网站,并通过 Jersey (JAX-RS)依赖创建spring boot项目</strong><br /> <img alt="创建spring boot项目" class="img-thumbnail" src="/assist/images/blog/9eee2ca48f664f0e8949e824feb21a90.png" /><br /> <strong>2.创建zip文件的项目。解压到自己电脑的某个地方。通过eclipse中的导入maven 已经存在的项目导入该项目</strong><br /> <strong>3.检查项目的maven依赖文件,看是否有加入spring-boot-starter-jersey的依赖。</strong> <pre> <code class="language-xml"><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies></code></pre> <h2>四.创建JAX-RS REST资源文件</h2> 现在创建一些JAX-RS资源用来做测试。我这里创建了一个UserResource class.<br /> <strong>UserResource.java:</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") @Path("/users") public class UserResource { private static Map<Integer, User> DB = new HashMap<>(); @GET @Produces("application/json") public Users getAllUsers() { Users users = new Users(); users.setUsers(new ArrayList<>(DB.values())); return users; } @POST @Consumes("application/json") public Response createUser(User user) throws URISyntaxException { if(user.getFirstName() == null || user.getLastName() == null) { return Response.status(400).entity("Please provide all mandatory inputs").build(); } user.setId(DB.values().size()+1); user.setUri("/user-management/"+user.getId()); DB.put(user.getId(), user); return Response.status(201).contentLocation(new URI(user.getUri())).build(); } @GET @Path("/{id}") @Produces("application/json") public Response getUserById(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user == null) { return Response.status(404).build(); } return Response .status(200) .entity(user) .contentLocation(new URI("/user-management/"+id)).build(); } @PUT @Path("/{id}") @Consumes("application/json") @Produces("application/json") public Response updateUser(@PathParam("id") int id, User user) throws URISyntaxException { User temp = DB.get(id); if(user == null) { return Response.status(404).build(); } temp.setFirstName(user.getFirstName()); temp.setLastName(user.getLastName()); DB.put(temp.getId(), temp); return Response.status(200).entity(temp).build(); } @DELETE @Path("/{id}") public Response deleteUser(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user != null) { DB.remove(user.getId()); return Response.status(200).build(); } return Response.status(404).build(); } static { User user1 = new User(); user1.setId(1); user1.setFirstName("John"); user1.setLastName("Wick"); user1.setUri("/user-management/1"); User user2 = new User(); user2.setId(2); user2.setFirstName("Harry"); user2.setLastName("Potter"); user2.setUri("/user-management/2"); DB.put(user1.getId(), user1); DB.put(user2.getId(), user2); } }</code></pre> <strong>Users.java</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import java.util.ArrayList; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") public class Users { @XmlElement(name="user") private ArrayList<User> users; public ArrayList<User> getUsers() { return users; } public void setUsers(ArrayList<User> users) { this.users = users; } }</code></pre> <strong>User.java</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; @XmlAttribute(name = "id") private int id; @XmlAttribute(name="uri") private String uri; @XmlElement(name = "firstName") private String firstName; @XmlElement(name = "lastName") private String lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } }</code></pre> <h2>五.Jersey配置</h2> <br /> <strong>1.现在我们有一个jax - rs资源,我们想从spring boot应用程序中访问它,其中包括Jersey依赖。让我们将此资源注册为Jersey资源。</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(UserResource.class); } }</code></pre> 查看@ component注释。它允许在spring引导自动扫描源文件夹中的java类时注册这个类。<br /> <br /> <strong>2.ResourceConfig提供了简化jax - rs组件注册的高级功能。</strong><br /> <br /> <strong>3.通过<code>SpringBootServletInitializer扩展spring boot项目</code></strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class JerseydemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { new JerseydemoApplication().configure(new SpringApplicationBuilder(JerseydemoApplication.class)).run(args); } }</code></pre> <h2>六.demo</h2> 启动spring boot项目,并测试资源<br /> <strong>Access /users resource<br /> <img alt="Access /users resource" class="img-thumbnail" src="/assist/images/blog/fdc261ca174b41cf88e9884c46db3762.png" /><br /> Access /users/1 resource<br /> <img alt="Access /users/1 resource" class="img-thumbnail" src="/assist/images/blog/0fb858b938bf41129a695db1e9d85a68.png" /></strong><br />  
  • java编程中采用Apache common.httpclient方式模拟POST请求

    java编程中采用Apache common.httpclient方式模拟POST请求java编程中采用Apache common.httpclient方式模拟POST请求 <pre> <code class="language-java">import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; public class HttpclientUtils { /** * 采用Apache common.httpclient方式模拟POST请求 * * @param url * @param params * @return * @throws HttpException * @throws IOException */ public static String doPost(String url, Map<String, String> params) throws HttpException, IOException { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); client.getParams().setContentCharset("UTF-8"); method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8"); List<NameValuePair> dataList = new ArrayList<>(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { dataList.add(new NameValuePair(entry.getKey(), entry.getValue())); } } if (!dataList.isEmpty()) { method.setRequestBody(dataList.toArray(new NameValuePair[0])); } client.executeMethod(method); String SubmitResult = method.getResponseBodyAsString(); return SubmitResult; } } </code></pre>
  • Java枚举使用场景举例

    Java枚举使用场景举例Java enum(枚举)使用package common.enums; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public enum OrderStatus {     待付款(100, "待提交"),     待发货(200, "欠费审批"),     待收货(300, "材料初审"),     待确认收货(400, "材料报送"),     待评价(500, "补正完成"),     订单完成(600, "过程管理");     int value;     String name;     OrderStatusEnum(int value, String name) {         this.value = value;         this.name = name;     }     public int getValue() {         return value;     }     public String getName() {         return name;     }     private static final List<Map<String, Object>> CODE_MAP = new ArrayList<>();     static {         for (OrderStatusEnum typeEnum : OrderStatusEnum.values()) {             Map<String, Object> map = new HashMap<>();             map.put("value", typeEnum.value);             map.put("name", typeEnum.name);             CODE_MAP.add(map);         }     }     public static List<Map<String, Object>> toData() {         return CODE_MAP;     }     public static OrderStatusEnum setValue(int value) {         for (OrderStatusEnum typeEnum : OrderStatusEnum.values()) {             if (typeEnum.value == value)                 return typeEnum;         }         return null;     } }枚举一般用来定义某些固定的状态以及值,比如上面的订单状态。然后通过toData又可以将状态值的数据返回给前端作为筛选条件使用。
  • spring security4认证流程及流程图spring security简单入门

    Java编程中spring security4是一个spring框架项目的一个安全方面的项目。主要用于用户认证,授权,角色认证Java编程中spring security4认证流程及流程图spring security简单入门<br /> 认证流程图:<br /> <img alt="spring security 认证流程图" class="img-thumbnail" src="/assist/images/blog/1d29964f-2a50-4c23-9e11-54a003e27b2b.jpg" /><br /> sample代码: <pre> <code class="language-java">package com.leftso.test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; public class AuthenticationExample { private static AuthenticationManager am = new SampleAuthenticationManager(); public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Please enter your username:"); String name = in.readLine(); System.out.println("Please enter your password:"); String password = in.readLine(); try { Authentication request = new UsernamePasswordAuthenticationToken(name, password); Authentication result = am.authenticate(request); SecurityContextHolder.getContext().setAuthentication(result); break; } catch (AuthenticationException e) { System.out.println("Authentication failed: " + e.getMessage()); } } System.out.println("Successfully authenticated. Security context contains: " + SecurityContextHolder.getContext().getAuthentication()); } } class SampleAuthenticationManager implements AuthenticationManager { static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>(); static { AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER")); } public Authentication authenticate(Authentication auth) throws AuthenticationException { if (auth.getName().equals(auth.getCredentials())) { return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES); } throw new BadCredentialsException("Bad Credentials"); } }</code></pre> <br /> 上面的例子,其中认证器只是简单的认证了密码与用户名相同则为合法用户,且设置角色为ROLE_USER<br /> <br /> <br />  
  • httpclient4.5使用详解 httpclient 4.5 post传递json参数

    httpclient4.5使用详解 httpclient 4.5 post传递json参数httpclient4.5使用详解 httpclient 4.5 post传递json参数 <pre> <code class="language-java">import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * 工具类 httpclient4.5 * * @author xq * */ public class HttpclientUtils { /** * post请求 json参数 * * @param url * @param bodyJsonParams * @param headers * @return * @throws IOException */ public static String doPost(String url, String bodyJsonParams, Map<String, String> headers) throws IOException { HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(bodyJsonParams)); if (headers != null && headers.keySet().isEmpty()) { Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); httpPost.addHeader(key, value); } } return execute(httpPost); } /** * post k-v参数 * * @param url * @param params * @param headers * @return * @throws IOException */ public static String doPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException { HttpPost httpPost = new HttpPost(url); if (params != null && params.keySet().isEmpty()) { List<NameValuePair> list = new ArrayList<>(); Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); list.add(new BasicNameValuePair(key, value)); } httpPost.setEntity(new UrlEncodedFormEntity(list)); } if (headers != null && headers.keySet().isEmpty()) { Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); httpPost.addHeader(key, value); } } return execute(httpPost); } /** * get请求 * * @param url * @param params * @param headers * @return * @throws IOException * @throws ClientProtocolException */ public static String doGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException { // 参数 StringBuilder paramsBuilder = new StringBuilder(url); if (params != null && params.keySet().isEmpty()) { if (url.indexOf("?") == -1) { paramsBuilder.append("?"); } List<NameValuePair> list = new ArrayList<>(); Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); list.add(new BasicNameValuePair(key, value)); } String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(list)); paramsBuilder.append(paramsStr); } HttpGet httpGet = new HttpGet(paramsBuilder.toString()); // 头 if (headers != null && headers.keySet().isEmpty()) { Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); httpGet.addHeader(key, value); } } return execute(httpGet); } /** * 执行请求并返回string值 * * @param httpUriRequest * @return * @throws IOException */ private static String execute(HttpUriRequest httpUriRequest) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { CloseableHttpResponse response = httpClient.execute(httpUriRequest); if (response.getStatusLine().getStatusCode() == 200) {// 请求成功状态 try (BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(response.getEntity().getContent()))) { String result=""; String tmp=null; while((tmp=bufferedReader.readLine())!=null){ result+=tmp; } return result; } } } return null; } } </code></pre>